Reputation: 1060
example of what I want to do is
@interface A<ObjectType> : NSObject
@end
@interface B<ObjectType> : NSObject
- (void)doSomething:(ObjectType)obj;
@end
@implementation B
- (void)doSomething:(id)obj {
**A<ObjectType> *a = [[A alloc] init];**
[a addObject:obj];
}
@end
Basically I want A to be allocated with the same type as B was allocated with.
The line within ** won't compile. What is the right syntax to do something like this?
Upvotes: 0
Views: 1941
Reputation: 53000
Objective-C does not have generics, Apple introduced something they term Lightweight Generics, and you may read the "lightweight" as "faux".
Here is Apple's own statement on what they do:
Allow you to specify type information for collection classes such as NSArray, NSSet, and NSDictionary. The type information improves Swift access when you bridge from Objective-C and simplifies the code you have to write.
Notice the "improves Swift access" and the lack of "improves Objective-C". These lightweight generics are essentially annotations for the Swift compiler when it is importing Objective-C types. On the Objective-C side maintaining the generic invariants is largely the responsibility of the programmer.
You can use the lightweight generic annotations (a) in an @interface
and (b) when declaring a variable whose type has lightweight generic annotations. You cannot otherwise use the annotations, in particular you do not use them in an @implementation
other than (b) above. Within the @implementation
for a lightweight generic annotated @interface
rather than use the "type parameters" from the annotations you use the id
type - as you have done with your doSomething:
method.
The latest Xcode/Clang will provide some checking of lightweight generic annotations in Objective-C, but it is limited and should in no way be taken as a guarantee that the generic conditions are being checked.
In summary, unless you are planning to interwork with Swift using the lightweight generic annotations in Objective-C is of little benefit, and it certainly does not give you "generics" in the usual sense (i.e. parametric generic types).
Undoubtedly not what you wanted to hear, but HTH
Upvotes: 4
Reputation: 471
is this ok for you?
@protocol ObjectType <NSObject>
- (void)addObject:(id)obj;
@end
@interface A : NSObject <ObjectType>
@end
@implementation A
- (void)addObject:(id)obj {
}
@end
@interface B : NSObject <ObjectType>
- (void)doSomething:(id<ObjectType>)obj;
@end
@implementation B
- (void)addObject:(id)obj {
}
- (void)doSomething:(id)obj {
id<ObjectType> a = [[A alloc] init];
[a addObject:obj];
}
@end
Upvotes: -1