Bridge to objc, how can it knows arguments types? - objective-c

I am writing a bridge from a language I am developing and ObjC.
There are several nice introspection C functions in the objective C runtime and I am able to retrieve arguments types for methods using method_getTypeEncoding.
The main problem is with object arguments which are returned as id (encoded as #) but what I would need is the real objc class name like NSString or NSNumber.
Is there a way to solve this issue without parsing the .h files?

Knowing something is an id allows you to know the size of the parameter, which is important when writing a scripting interface. Add another layer where you can dynamically verify assumptions using things like
[objectPassedIn isKindOfClass: [expectedType class]];
You want to be careful hardcoding things like, "Oh this is a string so look for __NSCFString" - because there's no way to know you'll get an instance of __NSCFString or another type. NSString is a class cluster - You could get any custom implementation back when using one.
The actual type of objects is not important to the Objective-C Runtime so you need to add your own layer. You might be able to get some useful info using Clang/llvm as a tool.

Related

NSManagedObject subclass generated +CoreDataProperties.m files not actually required?

When generating an NSManagedObject subclass xcode creates two extra files MyObject+CoreDataProperties.h & MyObject+CoreDataProperties.m to keep the CoreData stuff away from our own code.
This is nice but I noticed in a WWDC clip that they didn't have the +CoreDataProperties.m file in their example. So I tried removing these in my code and everything compiles and runs fine without them, they don't appear to be necessary at all.
Are they required in some way that I've overlooked, or if not, then why does xcode generate them at all?
The short answer:
No, it is not necessary.
The long answer:
Objective-C is a dynamic typing, late binding programming language. In a short form that means, that every type decision can be made at runtime instead of compile time and you can access properties of an and send messages to an object without knowing its type (class).
But it is not necessary for the Core Data framework and you as the user of Core Data and your model to know the type of an managed object for a entity type. It is even not necessary to have a specific type for an entity type. (I do not generate the classes very often and if I do, I do it manually.) Therefore in contrast to other programming languages these generated classes are not necessary to give the compiler a type.
However, the compiler wants to see at least every method at least one time to get the signature (parameter typing). Otherwise it would warn. Even it is possible to have working code like this …
NSManagedObject *person = …
NSString *firstName = [person firstName];
… for an entity type Person with a property firstName, the compiler will warn you, that he does not know anything about a method –firstName.
Instead you can type something like this:
NSManagedObject *person = …
NSString *firstName = [person valueForKey:#"firstName"];
(The compiler knows -valueForKey:, since this is a method declared in NSObject.)
Beside this you get benefits like code completion, check for typing errors and so on. But you do not need to use the code generation tool of Xcode. Simply declare such a class and at the properties at the interface. The accessors can be dynamically generated using #dynamic. (Personally I nearly never use the static code generation.)
Edit: Added the result of the discussion in the comments.
So having the interface (".h-file") of the category, the compiler knows enough to compile the whole code without warnings. This will work at runtime, if it is guaranteed – or checked at runtime – that a corresponding message can be dispatched. This makes sense in many situations from the very beginning of Objective-C, i. e. for forwarding and informal protocols. In the context of Core Data it is used to dynamically generate standard accessor methods. Everything works fine without any implementation.
However, one wants to have an implementation for some reasons, i. e. housekeeping on value changes. In such a case it is useful to have a stub implementation you can edit. But for standard behavior it is not necessary.

Is the `id` type used often writing Objective C programs?

I'm reading the book "Programming in Objective C" and he explained not too much on the id type and didn't give much exercise on it, so I'm wondering how often do you use id and if programmers most of the time avoid it? (since he explained some issues with it)
I'm sure it's used, would be great if you can mention some cases it is the only solution..like real life programming cases from some kind of app development.
id is the universal type in Objective C. It can represent a * of any Objective-C type, such as NSString *, NSArray *, etc. The neat thing about Objective-C is that you can send messages to id, and if the object on the other end understands the message, it will get processed as usual without the sender having to know the real type.
It's commonly used when defining anything generic. For example, NSArray is an array of ids; it's up to the programmer to put a specific kind of object in the container (e.g. NSNumber, NSString, etc.). It's used in a lot of other places in Objective-C (such as when defining IBActions for the interface builder, when defining init methods, etc.).
id is the generic object type in Objective-C. It can hold any object.
one real world example: parsing json you wont know, if the root element is a array or a dictionary. But id would take them both.
I use it a lot, but often in conjunction with a protocol definition: id<NetworkPrinterProtocol>. This means that it should be an object of any kind but it does fulfill the NetworkPrinterProtocol. Often used for defining delegates.
see WP: Objective-C — Dynamic Typing
The id is kind of like a catch-all data type. It is used to hold values of any type.
Common uses are for the return type of init... methods. It's used by the collection classes since they can hold any object. See the various getter methods return values and the various methods for adding/setting objects in the mutable version of collection classes.
It's also used in combination with protocols when you need a reference to an object that can be any class but must adhere to a protocol. Examples include many of the delegate properties such as the UITableView delegate.

Searching Functions in Objective C

I have a strange task. I need to get an array that contains all the functions in an objective c object. I then need to be able to tell if each function is a class method or not. Then I need to get the names (preferably an NSString) of each parameter and the type each parameter takes. Is there a way to do this? If not, does anyone know how to access the keys and values coded in the NSCoding Protocol function -(void)encodeWithCoder:(NSCoder*)aCoder; without using NSKeyedArchiver? What I am trying to do here is display a list of properties required to initialize an object. All my objects use class methods to initialize themselves. I am making a level editor that allows me to edit properties that differ between objects and I don't feel like writing getPropertyList and initWithProperties functions for every single object since I have already done this by implementing the NSCoding protocol.
I need to get an array that contains all the functions in an objective c object. I then need to be able to tell if each function is a class method or not.
Easy enough: you want class_copyMethodList(), which gets you just the instance methods for that class. To get the class methods, pass the class object, e.g. class_copyMethodList(object_getClass([NSString class]), &count);
Then I need to get the names (preferably an NSString) of each parameter and the type each parameter takes.
The parameter name part is probably not possible. They're not included in the method's metadata, and I'm pretty sure that they don't survive compilation at all; digging them out of the executable if they're there would certainly not be easy.
The types, however, are easily accessible via one of two runtime functions: either method_getTypeEncoding(), which gets you the signature string for the method's return and arguments, or method_getArgumentType(), which will let you loop over the argument types (the returned strings use the same code as the full type string).
If not, does anyone know how to access the keys and values coded in the NSCoding Protocol function -(void)encodeWithCoder:(NSCoder*)aCoder without using NSKeyedArchiver?
Are you talking about the particular implementation that you've made for encodeWithCoder:? You want the list of ivars implied by [coder encodeObject:firstIvar forKey:#"firstIvar"]; [coder encodeObject:secondIvar forKey:#"secondIvar"];? I'm not sure what that has to do with method signatures, but if so, you could make an NSCoder subclass that creates a dictionary from when you pass it as the coder and send encodeWithCoder: to your objects (see this answer I posted the other day).
What I am trying to do here is display a list of properties required to initialize an object.
What about a class method that returns an array with the names of the properties?
+ (NSArray *)essentialPropertyNames {
return [NSArray arrayWithObjects:#"firstIvar", #"secondIvar", nil];
}
That would probably be less effort than picking through the runtime/class metadata and wouldn't be any less odd.
All my objects use class methods to initialize themselves.
That sounds unusual at best. In Cocoa, instances should use some form of -init to do their initialization.

Why do we have NSNumber and NSTemporaryNumber as two different classes?

I went through the source code of GNUStep's NSNumber's implementation to understand how does factory method implementation works there.
From there What I could understand was we have NSNumber with blank implementation for all initWithXYZ kind of methods. and NSTemporaryNumber was acting like an intermediate class in the hierarchy that implemented all the initWithXYZ methods where it actually created objects of specific types , autoreleased itself and returned the created object.
Also allocWithZone was overridden to avoid creation of NSNumber object and to create object of NSTemporaryNumber if it was so otherwise create objects of specific types.
What I didn't understand was, can't the same things be done by NSNumber itself ?
why give blank implementations at all , create the object of specific type and then autorelease self.
Also if we have implementations of createXYZ methods in NSNumber itself, why have initWithXYZ methods ?
If I have to implement a factory implementation for my project where say I have two mediaItems, video , audio and photo etc.
for which I have separate classes and corresponding enums which I pass to initWithMediaType who will create an object of correct child class, return it and destroy itself.
Have two classes like NSNumber and NSTemporaryNumber: say Media and TemporaryMedia, one with blank implementations other with implementations as mentioned above ?
Should I do something like this ?
Is this the way we have to implement Factory pattern in Objective C ?
My question might seem silly biut I come from a Java, C++ background where things looked different.
The purpose might be the same but I am finding it difficult to understand the way Objective C does it since it does not have abstract classes.
Link to the source:
http://www.koders.com/objectivec/fid46956186C20201706AFE1744AA7AFEEE09D1FE5A.aspx
The point is that NSNumber is a class cluster. The class you actually end up with may be an NSIntNumber, an NSFloatNumber or one of several others. They all respond to the same messages as NSNumber (and, usually in this pattern will be subclasses of it, but that isn't required) so it makes no real difference to the caller.
When you call alloc there's no way to know what sort of object to create, so a neutral type is created and returned instead. It substitutes appropriately upon receiving an appropriate init.
So this pattern is for the implementation of class clusters. You can ignore it if writing a class that provides only instances of itself.

Why did Apple previously typedef reference (pointer) types but not now?

I've been wondering why Apple uses data types in Core Foundation that are typedef'd to a pointer type while in Cocoa they are not.
As an example, you would reference a UIColor object like UIColor * while a reference to a CGColor object would be CGColorRef? Or NSURL * and CFURLRef? Why not just always use CGColor * and CFURL *? Or conversely, why no UIColorRef or NSURLRef types, since you never access a UIColor or NSURL directly anyway?
Or for example, why is it id and not id *, since it is actually a pointer and can in fact be typecast to void *?
Specifically, is there some reason Apple had a habit of doing this in their older frameworks, but stopped doing it in Cocoa? Is it simply a matter of style?
What Matt said, but there is a bit more to it.
The typedefs in the C based APIs also allow the implementation details to be hidden. For example, you can have the following without ever defining the __CFURL structure in a public header.
typedef __CFURL *CFURLRef;
Objective-C has long had these kinds of features in the form of categories and, recently added, the ability to move instance variable declarations out of the header file. Expect that, over time, you will see all instance variables removed from the public header files in the SDK.
Note that the Cocoa frameworks long, long, pre-dated CoreFoundation.
As for why id is used instead of id *, that dates back to when Objective-C was first created in the early 1980s. Specifically, the notion of the language was that you would build "software integrated circuits" that could be "plugged together" like real ICs. The goal was to keep the C bits around as implementation details and, ideally, not exposed in your APIs.
As for why you end up with NSString * instead of NSString, that is largely exactly because of the C underpinnings of the language. I wrote a fairly detailed answer to a slightly different SO question that is relevant.
You'll probably also find this answer relevant, too.
The reason for NSURL* vs CFURLRef is pretty much that it's just coding style. Cocoa is an Objective-C API and the general style in Objective-C is to not have a typedef whereas Core Foundation is a C API and the general style of it is to use a typedef. It's pretty much down to coding style.
id vs id* - I am not entirely sure with that, but my guess is it's historical and they just wanted to have the base "object" to be without the *. I don't know for sure the history of that, though. But again it'll just be a style thing.