Rakesh
Rakesh

Reputation: 3399

Extension for a Foundation class

Since the .m files for the foundation classes(say for NSString) are not available , I was thinking if I could declare an extension, inside the .m file of a category declared on the same class. I was successful in creating a private method which doesn't use any instance variable inside. But when I tried to access an iVar declared inside the interface its causing problems.
*This didn't have a purpose as such, was just trying out things.

What I did was declare a category on NSString :

NSString+TestInterface.h

@interface NSString (TestInterface)
@end

NSString+TestInterface.m

@interface NSString () {

    NSString *myVar;
}
@property (strong) NSString *myVar;
-(void)myPrivateMethod;
@end


@implementation NSString (TestInterface)
-(void)myPrivateMethod{
    myVar=@"random";
//    [self setValue:@"check" forKey:@"myVar"];

    NSLog(@"Private %@",myVar);
//    NSLog(@"Private %@",[self valueForKey:@"myVar"]);
}

@end

When I do it this way I get the following compiler error:

Undefined symbols for architecture x86_64:
"_OBJC_IVAR_$_NSString.myVar", referenced from: -[NSString(TestInterface) myPrivateMethod] in NSSTring+TestInterface.o ld: symbol(s) not found for architecture x86_64

Can someone tell me what is happening?

Upvotes: 1

Views: 218

Answers (2)

Hermann Klecker
Hermann Klecker

Reputation: 14068

You cannot add instance variables in an extension/category of a foreign class for which you do not own the implementation (.m file).

You could of course add methods that act as setter and getter. For the storage of the acutal values you could make use of objc_setAssociatedObject which is some sort of global storage where you associate a value with a key and with an instance of an object.

Here it is nicely explained, discussed and exaples given: What is objc_setAssociatedObject() and in what cases should it be used?

Upvotes: 4

user529758
user529758

Reputation:

You can only define new instance variables using class extensions in the same translation unit (file) which the original, primary implementation of the class resides in. This means that you can't effectively add instance variables to a class you don't have the source code for.

Upvotes: 2

Related Questions