Does Objective-C have an equivalent to java annotations?

前端 未结 8 1088
后悔当初
后悔当初 2020-12-28 09:10

Does Objective-C have an equivalent to java annotations?

What\'s I\'m trying to do is create a property and be able to somehow access some metadata about it.

8条回答
  •  萌比男神i
    2020-12-28 09:47

    Does Objective-C have an equivalent to java annotations?

    Not exactly an equivalent, but there is, and it's better. In Objective-C, the compiler has to store some type and name information in the compiled code (because the language is highly dynamic, a lot of things happen at runtime as opposed to compile time), for example method names ("selectors"), method type signatures, data about properties, protocols, etc. The Objective-C runtime library then has access to this data. For example, you can get the list of properties an object has by writing

    id object = // obtain an object somehow
    unsigned count;
    objc_property_t *props = class_copyPropertyList([object class], &count);
    

    Or you can check what class an object belongs to:

    if ([object isKindOfClass:[NSArray class]]) {
        // do stuff
    }
    

    (Yes, part of the runtime library is itself wrapped into some methods of NSObject for convenience, others only have C function APIs.)

    If you specifically want to store custom metadata about an object or a class, you can do that using associated references.

提交回复
热议问题