COOKIES
COOKIES

Reputation: 444

Access annotated property in Objective-C

I’ve searched around for this but found no information at all. Say I create a property like so:

@property (nonatomic, strong, readwrite) NSString *someString __attribute((annotate(“Try to access this text?)));

How could I access the text in the annotation part of the property? I’m guessing I’d have to utilize Objective-c runtime but I found no information there either.

Upvotes: 0

Views: 232

Answers (1)

Mitchell Currie
Mitchell Currie

Reputation: 2809

First off, sales pitch - swift would make this easily transparent with optionals. Since you are using objective-c here's how I would do it:

@interface SomeModel {
static NSString * const _requiredProperties[] = {
        [0] = @"first",
        [1] = @"second"
    };
}

@property(nonatomic, strong) NSString *first;
@property(nonatomic, strong) NSString *second;

@end



-(BOOL) doLoad:(...) {
    //map properties here
    Bool success = YES;
    foreach(NSString property in _requiredProperties {
        success &= ([self valueForKey: property] != nil);
    }
return success;
}

The objective-C language doesn't contain the types of constructs you need. Keep it simple, handle missing properties elegantly.

Also if it's JSON, there's plenty of frameworks available to help. Unsure of your mapping here.

Alternatively you can query the protocol, and use the fact it is in a protocol to determine if required.

See this hello world like example that prints out the protocols in the required protocol - sadly the third param which is "YES" for required seems to include optionals for me on OSX. So I made a separate protocol for optionals. This might help you.

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@protocol TestProtocolRequired
@required
@property(nonatomic, strong) NSString *firstName;
@property(nonatomic, strong) NSString *lastName;
@end

@protocol TestProtocolExtended
@property(nonatomic, strong) NSString *address;

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        unsigned int outCount, i;
        objc_property_t *properties = protocol_copyPropertyList2(@protocol(TestProtocolRequired), &outCount, YES, YES);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
        }

    }
    return 0;
}

It prints out

firstName T@"NSString",&,N
lastName T@"NSString",&,N

Upvotes: 1

Related Questions