I want to create a new object, one of the property is (readonly). Here is my code:
1/ My class (.h + .m)
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@property (readonly) NSString* myProperty;
@end
#import "MyClass.h"
@implementation MyClass
@end
2/ My class extension (.h)
#import "MyClass.h"
@interface MyClass ()
@property (readwrite) NSString* myProperty;
@end
3/ MyClassCategory (.h + .m)
#import "MyClass.h"
@interface MyClass (MyClassCategory)
+ (MyClass*) creatNewObject:(NSString*) mypro;
@end
#import "MyClass+MyClassCategory.h"
#import "MyClass_MyClassExtension.h"
@implementation MyClass (MyClassCategory)
+ (MyClass*) creatNewObject:(NSString*) mypro {
MyClass* newObject = [[MyClass alloc] init];
newObject.myProperty = mypro;
NSLog(@"New object have been created%@", newObject);
return newObject;
}
@end
#import <Foundation/Foundation.h>
#import "MyClass.h"
#import "MyClass+MyClassCategory.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
MyClass* newObject1 = [MyClass creatNewObject:(@"I am the new object!")];
NSLog(@"New object have been created%@", newObject1);
}
return 0;
}
after running the code in the main method, I got
2014-09-25 21:53:52.204 MyClass[2811:303] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyClass setMyProperty:]: unrecognized selector sent to instance 0x100109e10'
I want to be enables edits to the properties of an existing class instance from category.
Can you help me please? Thank you.
In MyClass.m
, you also need to include the extension header.
#import "MyClass_MyClassExtension.h"
Otherwise the compiler won't see myProperty
is redeclared as a read-write property while generating the implementation of MyClass
.