goo
goo

Reputation: 2280

Objective -c: String length from instancetype

Very new to Objective c. My interface and implementation looks like this:

// MyAuth.h
// @interface
+ (instancetype)sharedToken;

// MyAuth.m
//@implementation
+ (instancetype)sharedToken {
   static MyAuth *_sharedToken = nil;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       _sharedToken = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
   });
   return _sharedToken;
}

Now I'm trying to get the length of the sharedToken but am stuck here. What I've tried

[MyAuth sharedToken].length // doesn't work

How can I get the length of `sharedToken

Upvotes: 0

Views: 149

Answers (1)

jscs
jscs

Reputation: 64022

You want a string pulled from NSUserDefaults to be accessible everywhere in your app, via this method.

The return type of the method needs to be the type of the object you're actually returning:

+ (NSString *)sharedToken;

instancetype says that the method returns an instance of the class which runs the method.

The pointer you use for the string should also have the correct type:

static NSString *_sharedToken = nil;

Now the compiler will let you send length to the result of the method call.

Upvotes: 1

Related Questions