Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use generics on obj-c?

With the new xcode7 Apple introduced generics and nullability to Objective-C ( Developer guide )

But it seems to be very different from what we have on swift.

Nullability:

- (nonnull NSString *)something {
    return nil;
}

This should raise a warning! And you can even assign the return value of this method to a nonnull variable like:

//@property (copy, nonnull) NSString *name

obj.name = [obj something]; 

Generics: Looking this example:

@property (nonatomic, strong, nonnull) NSMutableArray <UIView *> *someViews;

a warning is raised when something different from a UIView is inserted on the array

[self.someViews addObject:@"foobar"]; //<- this raises an error

but not in this case:

self.someViews = [@[@"foobar"] mutableCopy];

nor in this case:

NSString *str = [self.someViews firstObject];

So the question is, I'm using generics and nullability in a wrong way or they are far away from the Swift implementation?

like image 627
IgnazioC Avatar asked Nov 10 '22 08:11

IgnazioC


1 Answers

self.someViews = [@[@"foobar"] mutableCopy];

mutableCopy is inherited from NSObject, where it is declared to return id. It is not declared by NSArray specifically and NSArray des not decide the return type.

NSString *str = [self.someViews firstObject];

This does give a warning for me.

like image 119
newacct Avatar answered Nov 14 '22 21:11

newacct