Setting static variables in Objective-C

I cannot find a way to set the static int that I created to assign unique identifiers for each stored object to read-only memory. The following gives me the "no setter method" setIdGen 'to assign a property.

-(void)viewDidLoad
{
    PlayerMenuController.idGen = [[NSUserDefaults standardUserDefaults] floatForKey:@"idGen"];
}

As above, I tried to create a static setIdGen method that would return bad access errors and make NSIntegers my own set methods. My static NSMutableArray gave the same errors when I tried to assign it with =, but worked fine when using setArray.

IdGen method:

+ (int) idGen
{
    /*static int idGen;
    if(!idGen)
    {
        idGen = 0;
        NSLog(@"idGen reset");
    }*/
    return self.idGen;
}
+5
source share
3 answers

Update 2017

Xcode 8 introduced the properties of the Objective-C class, from the release notes:

Objective-C , Swift. @property (class) NSString *someStringProperty; .

, :

@interface PlayerMenuController : NSObject

@property (class) int idGen;

@end

, , . , , , copy, .


, , Objective-C - .

...

@property , , , ( Xcode 4.6.1, "", , , , ) , , @property.

:

@interface PlayerMenuController : NSObject

// a class "property"
+ (int) idGen;
+ (void) setIdGen:(int)value;

@end

:

@implementation PlayerMenuController

static int idGen = 0;

+ (int) idGen { return idGen; }
+ (void) setIdGen:(int)value { idGen = value; }

@end

:

NSLog(@"initial value: %d", PlayerMenuController.idGen);
PlayerMenuController.idGen = 42;
NSLog(@"updated value: %d", PlayerMenuController.idGen);

:

initial value: 0
updated value: 42

, " " - , , ; -)

+40

, , , , ( )

- objc/runtime.h

+(int) idGen
{
    NSNumber* idGen = objc_getAssociatedObject(self, @selector(idGen));

    if (idGen == nil)
    {
        idGen = @0;
    }
    else
    {
        idGen = @([idGen intValue] + 1);
    }

    self.idGen = [idGen intValue];

    return [idGen intValue];
}

+(void)setIdGen:(int)idGen
{
    objc_setAssociatedObject(self, @selector(idGen), @(idGen), OBJC_ASSOCIATION_RETAIN);
}
+3

self.idGen, int . , :

 + (int) idGen {
     static int idGen;
     return idGen;
   }
+1

All Articles