Jakub
Jakub

Reputation: 13860

NSObject subclass as a property

I want to use my class as a property in my project. The idea is that i have a class which contains all list ellements. The basic idea i show below in graph:enter image description here So i have a myContainerClass object, and i want to do in some other class: @property (strong,nonatomic) MyContainerClass *obj; and here i have error! I figure out that i can only use Foundations type as a @property. But Why? What is replacement for doing that (passing an object)?

Upvotes: 0

Views: 278

Answers (3)

JeremyP
JeremyP

Reputation: 86651

No, you can use any class you like as a property

@property (nonatomic, strong) MyContainerClass* obj;

is perfectly legal provided that the compiler knows that MyContainerClass is a class. To do that in the header file, the best way is to use an @class forward declaration:

@class MyContainerClass;

@interface SomeOtherClass : NSObject

// method an property declarations

@property (nonatomic, strong) MyContainerClass* obj;

@end

And then include the header file in the implementation:

#import "MyContainerClass.h"

@implementation SomeOtherClass

@synthesize obj;

// other stuff

@end

Upvotes: 2

uiroshan
uiroshan

Reputation: 5181

What is the error you are getting? May be you are not importing MyContainerClass to where you want to use it.

#import "MyContainerClass.h"

Upvotes: 1

Eimantas
Eimantas

Reputation: 49354

Declare a category for an object that you want to add your property to:

@interface NSObject (MyContainerClassAdditions)

@property (nonatomic, strong) MyContainerClass *myContainerClass

@end

Then implement the setter and getter methods using objective c associated object trick:

#import <objc/runtime.h>

@implementation NSObject (MyContainerClassAdditions)

- (void)setMyContainerClass:(MyContainerClass *)myContainerClass {
    objc_setAssociatedObject(self, "myContainerClass", myContainerClass, OBJC_ASSOCIATION_ASSIGN);
}

- (MyContainerClass *)myContainerClass {
    return objc_getAssociatedObject(self, "myContainerClass");
}

@end

Upvotes: 0

Related Questions