Search code examples
objective-cxcode4

How can I get a method to return a Random object of type NSObject


I as a learning exercise of Objective C I need to write a method that returns a Random NSObject.
The approach that I tried to follow was to trying to get a list of all runtime objects and the itirate through and get an NSObject and return that.

Firstly I am not sure if that is the best approach. Secondly the code I am using is based on this and objc_getClassList link but in Xcode4 I am getting compile time error

warning: Semantic Issue: Implicit declaration of function 'objc_getClassList' is invalid in C99
warning: Semantic Issue: Implicit declaration of function 'classIsSubclassOfClass' is invalid in C99

I have tried adding following headers but no good

#import <objc/runtime.h>
#import <objc/objc-class.h>
#import <objc/objc-runtime.h>

but neither helped me and still have the warning.

So can I please some help with these two things
1- Is this the right approach and what is if not to achieve what I am trying to achieve
2- How can I get this code to not give warnings in Xcode 4.


Solution

  • Well, objc_getClassList is declared in objc/runtime.h, so including or importing that should do it.

    For the other part, you simply need to declare your function before you use it. At the top level of the file, or in a file that you then include, you put the function header, without the body:

    BOOL classIsSubclassOfClass( const Class aClass, const Class subclass );
    

    This lets the compiler know about the function; you can then #include this declaration in any file that needs to use the function, while defining it (i.e., filling out the body) wherever you like.