objective-c question regarding NSString NSInteger and method calls

10,009

Solution 1

Your init method looks fine, and if you're only dealing with integer values, you do want to use NSInteger as opposed to NSString or even NSNumber. The one thing you might want to change is the parameter you're passing should be (NSInteger), not (NSInteger *) - an NSInteger is not an object, but in Objective-C is a primitive type similar to int.

You can build the image name by using NSString's stringWithFormat: selector, as such:

NSInteger myInteger = 12;
NSString *imageString = [NSString stringWithFormat:@"image%d.png", myInteger];

Solution 2

Just to expand on what Tim mentioned, an NSInteger is actually just a #define. On 32-bit architectures, it's equivalent to an int and on 64-bit architectures it's a long.

If you need to treat an integer as an object (to put it in an NSDictionary, for instance), you can wrap it in an instance of NSNumber using numberWithInteger:.

Hope that helps!

Share:
10,009
Meltemi
Author by

Meltemi

Updated on June 05, 2022

Comments

  • Meltemi
    Meltemi almost 2 years

    I like to create an instance of a custom class by passing it a value that upon init will help set it up. I've overridden init and actually changed it to:

    - (id)initWithValue:(NSInteger *)initialValue;
    

    i'd like to store this value in a property of the instantiated object and use the value to generate the filename of a UIImage that will be associated with it.

    My question is how best to go about this in Cocoa/Obj-C. is an NSInteger the best parameter for my needs or would an NSString be better? Or is there another design pattern? I'm not familiar with all the creative methods available to help in this situation. Assume my class properties are:

    @interface MyView : UIView {
    UIImage *image;
    NSInteger value;
    

    If I stick with the NSInteger as a parameter I can easily assign value to it. but then would need to generate "image12.png" from that value (assume NSInteger = 12) to set up my UIImage. Something like "image"+initialValue+".png". Which I believe is verbosely expressed in Obj-C as:

    NSString *myValue = @"image";
    [myValue stringByAppendingString:[initialValue stringValue]]; //NSInteger may not respond to stringValue?!?
    [myValue stringByAppendingString:@".png"]
    

    This is where my understanding of Obj-C breaks down. Feels to me like this should be easier but I'm still confused.

    Now if initialValue was an NSString with the value of @"12" maybe it is? then self.value = [initialValue integerValue];

    and I could build image with multiple stringByAppendingString calls. Just seems tedious for something so simple in other languages.

    What's best way to handle something like this?