1

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?

2 Answers 2

4

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?

1
  • Thanks. I didn't know about objc_setAssociatedMethod. +1
    – Rakesh
    Jun 12, 2013 at 12:34
2

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.

3
  • Alright. But why doesn't the setValue:ForKey: throw an exception while valueForKey: does?
    – Rakesh
    Jun 12, 2013 at 12:35
  • @Rakesh IDK. I've just tried it and for me, it did raise an exception.
    – user529758
    Jun 12, 2013 at 12:39
  • Might have been my carelessness, it throws for me too. Thanks.
    – Rakesh
    Jun 12, 2013 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.