NSFastEnumeration object casting in ARC - objective-c

I'm trying to implement the countByEnumeratingWithState:objects:count: method from the NSFastEnumeration protocol on a custom class.
So far I have it iterating through my objects correctly, but the objects that are returned aren't Objective-C objects but rather the core foundation equivalents.
Here's the part of the code that sets the state->itemsPtr:
MyCustomCollection.m
- (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState *)state
objects: (id __unsafe_unretained *)buffer
count: (NSUInteger)bufferSize {
// ... skip details ...
NSLog(#"Object inside method: %#", someObject);
state->itemsPtr = (__unsafe_unretained id *)(__bridge void *)someObject;
// ... skip details ...
}
Then I call the 'for..in' loop somewhere else on like this
SomeOtherClass.m
MyCustomCollection *myCustomCollection = [MyCustomCollection new];
[myCustomCollection addObject:#"foo"];
for (id object in myCustomCollection) {
NSLog(#"Object in loop: %#", object);
}
The console output is:
Object inside method: foo
Object in loop: __NSCFConstantString
As you can see, inside the NSFastEnumeration protocol method the object prints fine, but as soon as it gets cast to id __unsafe_unretained * I lose the original Objective-C corresponding class.
To be honest I'm not quite sure how the (__unsafe_unretained id *)(__bridge void *) casting works in this case. The (__unsafe_unretained id *) seems to cast to match the right type itemsPtr needs. The (__bridge void *) seems to cast to a pointer of type void with __bridge used to bridge the obj-c world to the CF world. As per the llvm docs, for __bridge:
There is no transfer of ownership, and ARC inserts no retain operations
Is that correct?
From my understanding __NSCFConstantString is just the core foundation equivalent of NSString. I also understand that with ARC you need to bridge from Objective-C objects to CoreFoundation equivalents because ARC doesn't know how to manage the memory of the latter.
How can I get this working so that the objects in my 'for..in' loop are of the original type?
Also note that in this case I'm adding NSStrings to my collection but in theory it should support any object.
UPDATE
Rob's answer is on the right track, but to test that theory I changed the for loop to this:
for (id object in myCustomCollection) {
NSString *stringObject = (NSString *)object;
NSLog(#"String %# length: %d", stringObject, [stringObject length]);
}
In theory that should work since the objects are equivalent but it crashes with this error:
+[__NSCFConstantString length]: unrecognized selector sent to class
It almost looks like the objects returned in the for loop are classes and not instances. Something else might be wrong here... Any thoughts on this?
UPDATE 2 : SOLUTION
It's as simple as this: (thanks to CodaFi
state->itemsPtr = &someObject;

You're incorrectly casting someObject. What you meant is:
state->itemsPtr = (__unsafe_unretained id *)(__bridge void *)&someObject;
(Let's get rid of those awful casts as well)
state->itemsPtr = &someObject;
Without the address-of, your variable is shoved into the first pointer, which is dereferenced in the loop. When it's dereferenced (basically, *id), you get the underlying objc_object's isa class pointer rather than an object. That's why the debugger prints the string's value inside the enumerator call, and the class of the object inside the loop, and why sending a message to the resulting pointer throws an exception.

Your code is fine the way it is. Your debug output is revealing an implementation detail.
NSString is toll-free-bridged with CFString. This means that you can treat any NSString as a CFString, or vice versa, simply by casting the pointer to the other type.
In fact, under the hood, compile-time constant strings are instances of the type __NSCFConstantString, which is what you're seeing.
If you put #"hello" in your source code, the compiler treats it as a NSString * and compiles it into an instance of __NSCFConstantString.
If you put CFSTR("hello") in your source code, the compiler treats it as a CFStringRef and compiles it into an instance of __NSCFConstantString.
At run-time, there is no difference between these objects in memory, even though you used different syntax to create them in your source code.

Related

pointer pointer in objective-c

In c++ i would do the following,
Object* obj1;
Object* obj2;
Object** targetObj;
void SetTargetToObj1()
{
targetObj = &obj1;
}
void SetTargetToObj2()
{
targetObj = &obj2;
}
void ValueChanged()
{
//So if SetTargetToObj2() was called before ValueChanged() we
// would be changing some data on obj2
(*targetObj)->ChangeSomeData();
//or, we obj2 is null we could assign a new object to it via targetObj
(*targetObject) = new Object();
//now obj2 is pointing to our new object
}
Im wondering if there is a way in obj-c to do this same thing with NSObjects?
Pointers to pointers are not so simple under ARC.
When you declare, say, an instance variable:
NSObject *someObject;
you are implicitly declaring:
NSObject * __strong someObject;
i.e. a strong pointer. Strong is just one of the ownership qualifiers, you can also have weak and autoreleasing qualifiers.
Now taking the example in your comment:
NSDate **targetDate;
you get the error "pointer to non-const type 'NSDate *' with no explicit ownership". This is because ARC needs to know the ownership qualification of the pointer your pointer is referring to (read it slowly! ;-)). i.e ARC is asking you to type the variable instead as:
NSData * 'some ownership qualifer' * targetDate;
which, once you've decoded C's type priority rules, is a "pointer to a 'some ownership qualifier' pointer to an NSDate".
The error message includes "non-const" as this is all about writing via your pointer to pointer - ARC still needs to know how to handle the store, which depends on whether the pointed at reference is strong, weak, etc.
In your simple case the following should do:
NSObject *obj1;
NSObject *obj2;
NSObject * __strong * targetObj;
and then when doing (*targetObj) = ... etc. ARC knows what to do for memory management - which in this case is to release the old value in the variable referenced by targetObj as well as assigning the new reference into that variable.
Essential reading is Automatic Reference Counting and Transitioning to ARC Release Notes - in particular look up NSError in the latter as it explains how the common pattern of declaring error parameters as NSError ** is handled under ARC.
The code you have right there is already fine. If Object is in fact an obj-c object then this exact code is what you want. The only quirk is potential memory management issues (e.g. does targetObj need to retain the thing it's pointing to?)

Passing object pointer to performSelector:withObject results in EXC_BAD_ACCESS

Here is the problem:
I am passing a pointer to an object to performSelector:withObject via [NSValue valueWithPointer:] for example like this:
// GVertex is NSObject subclass
GVertex *vertex = [[GVertex alloc] initWithX:5.0f andY:4.5f]];
GVertex **vertexPtr = &vertex;
// later in code when I need to process the vertex
[self performSelector:#selector(processVertex:) withObject:[NSValue valueWithPointer:vertexPtr]];
then in my processVertex:(NSValue *)vertexValue method I want to get the passed vertex and I do it like this:
- (void)parseVertex:(NSValue *)vertexValue
{
GVertex *vertex = (GVertex *)[vertexValue pointerValue];
...
[vertex setFlags:32]; <<-- This gives me EXC_BAD_ACCESS
...
}
I have tried many combinations of (*) and (&) everywhere but can't get it to work.
What am I doing wrong ? Thanks.
Why don't you just pass your vertex object:
[self performSelector:#selector(processVertex:) withObject:vertex];
and change your method declaration to:
- (void)parseVertex:(GVertex *)vertex {
[vertex setFlags:32];
}
The pointer you're putting into the NSValue is a pointer to a pointer (or the address of a pointer), but you're retrieving it as if it's a plain object pointer. Moreover, the pointer whose address you're taking is a local variable -- that address is going to be garbage in the context of a new method.
This should work if you just store the (single) pointer in the NSValue:
[self performSelector:#selector(processVertex:) withObject:[NSValue valueWithPointer:vertex]];
Beware of memory management issues, however -- NSValue does not copy or take ownership of the memory at that pointer.

What does Objective-C actually do when you declare an object?

I have read the memory management guide from Apple and I don't see where this case is explained...
Many times, especially when writing a class method to return an instance of a class, I'll start it out like this, because that's how I've seen it done, and it works.
[NOTE] This code is from memory - I'll update it when I get home to show an example that really works (I made this up to illustrate it, but obviously I don't recall it well enough to construct something that makes sense...
[EDIT] Here's my actual method - of course everyone was right that I must be calling alloc which I am.
+ (id)player
{
Player *player = nil;
if ((player = [[[super alloc] initWithFile:#"rocket.png"] autorelease])) {
[player setProjectileType:kProjectileBullet];
[player setProjectileLevel:1];
[player setInvincible:YES];
[player setEmitter:[CCParticleSystemQuad particleWithFile:#"exhaust.plist"]];
[[player emitter] setPosition:ccp(0.0, player.contentSize.height/2)];
[player addChild:player.emitter];
}
return player;
}
So what I got from the responses is:
* Declaring the instance just gets me a pointer to a memory location and tells Xcode what class the object will be.
* Setting the pointer to nil pretty much just sets it to zero - keeping it from having garbage in it (right?)
* Since I'm autoreleasing the instance, the object that is returned is also autoreleased.
Thanks for helping me understand this!
Can someone explain what the compiler does when it sees this?
DooDad* aDooDad = nil;
If you are really interested in what the compiler does, the answer is: the compiler will reserve some memory on the stack for the local variable aDooDad, which is a pointer type (it is generally 64 or 32 bits in size depending on the processor). That pointer is then initialized to contain nil (usually 0x00..00).
A statement like this:
DooDad* aDooDad = [[DooDad alloc] init...];
makes use of pointer variable aDooDad to store the address in memory of the object that is further allocated (which is the address of memory reserved by alloc).
So, in the end,
DooDad* aDooDad = nil;
is not declaring an object, just a variable whose content is interpreted as the address of an object of DooDad type. Such declaration, therefore, is just like any other declaration you know, e.g. when initializing an int to 0, so that later you can assign it some value in an if statement.
A statement like:
[aDooDad doSomething];
is interpreted by the Objective-C runtime system like: send message doSomething to the object whose address is stored in aDooDad. If that address is nil no message is sent. On the other hand, if you dereference a nil pointer: *aDooDad you'll get undefined behavior.
Pointers are pretty low level stuff. I hope this helps.
If you're familiar with C or C++, variables can be created in one of two ways, statically on the call stack, or dynamically on the heap. Variable memory created on the stack is is reclaimed when the current stack frame goes out of scope, so you never need to worry about creating or destroying it. In Objective-C, objects are always dynamically created. Primitives (like int, float, pointers, etc), can either be statically or dynamically created. For illustration:
- (id)something {
NSObject myObject; // Illegal static object allocation
NSObject* myObject; // Legal primitive (pointer) static allocation
int myInt; // Legal primitive static allocation
int* myIntPtr; // Legal primitive (pointer) static allocation
}
So when you say DooDad* dodad = nil;, you're creating a primitive (pointer to a DooDad) on the stack. Being a stack variable, you don't alloc or dealloc it, just like you wouldn't worry about alloc'ing or dealloc'ing any of the memory in the following method:
- (id)allStackVariables {
int myInt = 0;
float myFloat = 0.0f;
float* myFloatPtr = NULL;
NSObject* myObject = nil;
}
Setting it to nil simply sets the contents of the variable to whatever the compiler defines to be nil, something like 0x000000 in hex. Saying DooDad* dooDad = nil; is conceptually identical to saying something like int myInt = 0;
Declaring simple gives you a pointer you can use later. No memory is allocated.
Not sure what the intent of the method you posted, but it seems wrong on many levels. It will return nil, always. Unless it's an initializer method, it should not call [self init]. If it is an initializer method, it should return self and be named something like "init..."

Why does NSString respond to appendString?

I was playing with the respondsToSelector method in Objective-C on MacOS-X 10.6.7 and Xcode 4.0.2, to identify if an object would respond to certain messages. According to the manuals, NSString should not respond to appendString: while NSMutableString should. Here's the piece of code which tests it:
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *myString = [[NSString alloc] init];
if ([myString respondsToSelector:#selector(appendString:)]) {
NSLog(#"myString responds to appendString:");
} else {
NSLog(#"myString doesn't respond to appendString:");
}
// do stuff with myString
[myString release];
[pool drain];
return 0;
}
and here's the output:
Class02[10241:903] myString responds to appendString:
I'd sort of expected the opposite. How does an NSString object respond to appendString: ? What's going on here that I'm missing ?
Short answer: That string is of type NSCFString, a class that inherits from NSMutableString, hence it responds to the selectors for the methods declared in NSMutableString, including superclasses.
Not so short answer: Foundation strings are toll-free bridged with Core Foundation strings. Developers use the opaque types CFStringRef (bridged with NSString) and CFMutableStringRef (bridged with NSMutableString) to refer to these strings so, at first glance, there are two different types of strings: immutable and mutable.
From a Core Foundation internal implementation perspective, there’s a private type called struct __CFString. This private type keeps a bit field that stores, amongst other information, whether the string is mutable or immutable. Having a single type simplifies implementation since many functions are shared by both immutable and mutable strings.
Whenever a Core Foundation function that operates on mutable strings is called, it first reads that bit field and checks whether the string is mutable or immutable. If the argument is supposed to be a mutable string but it in fact isn’t, the function returns an error (e.g. _CFStringErrNotMutable) or fails an assertion (e.g. __CFAssertIsStringAndMutable(cf)).
At any rate, these are implementation details, and they might change in the future. The fact that NSString doesn’t declare -appendString: doesn’t mean that every NSString instance doesn’t respond to the corresponding selector — think substitutability. The same situation applies to other mutable/immutable classes such as NSArray and NSMutableArray. From the developer perspective, the important thing is that the object that’s been returned is of a type that matches the return type — it could be the type itself or any subtype of that type. Class clusters make this a tad more convoluted but the situation is not restricted to class clusters per se.
In summary, you can only expect that a method returns an object whose type belongs to the hierarchy (i.e., either the type itself or a subtype) of the type for the return value. Unfortunately, this means that you cannot check whether a Foundation object is mutable or not. But then again, do you really need this check?
You can use the CFShowStr() function to get information from a string. In the example in your question, add
CFShowStr((CFStringRef)myString);
You should get an output similar to:
Length 0
IsEightBit 1
HasLengthByte 0
HasNullByte 1
InlineContents 0
Allocator SystemDefault
Mutable 0
Contents 0x0
where
Mutable 0
means that the string is in fact immutable.
This probably has to do with the implementation. NSString is a class cluster, which means that NSString is just a public interface and the actual implementing class is different (see what the class message gives you).
And at the same time NSString is also toll-free bridged to CFString, meaning that you can switch before those two types freely just by casting:
NSString *one = #"foo";
CFStringRef two = (CFStringRef)one; // valid cast
When you create a new string you really get a NSCFString back, a thin wrapper around CFString. And the point is that when you create a new mutable string, you also get an instance of NSCFString.
Class one = [[NSString string] class]; // NSCFString
Class two = [[NSMutableString string] class]; // NSCFString
I guess this was convenient from the implementation point of view – both NSString and NSMutableString can be backed by a common class (= less code duplication) and this class makes sure you don’t violate the immutability:
// “Attempt to mutate immutable object with appendString:”
[[NSString string] appendString:#"foo"];
There’s a lot of guess work in this answer and I don’t really understand the stuff, let’s hope somebody knows better.
You should not make assumptions about a method being not there. That method might be used internally or for whatever reason it exists. Technically, it's just private API.
You only have a contract to the public declarations (docs), and they don't show that message. So be prepared to get into trouble rather quickly if you use other features.

What does the "*" mean in Objective C?

Sometimes I encounter code that has *, sometimes **. Can anyone explain what they mean in Objective C? (I used to be a Java programmer, with experience in C/C++.)
The * denotes that you are using a pointer to a variable, and is most commonly used to store a reference to an Objective-C object, objects which can only live on the heap and not the stack.
Pointers are not a part of Objective-C exclusively, but rather a feature of C (and therefore its derived languages, of which Objective-C is one of them).
If you are questioning the difference between * and **, the first denotes a pointer, whereas the second denotes a pointer to a pointer; the advantage of the latter to the former is that when passing in an object using ** in a method parameter, the method can then change this parameter and the new value is accessible in the calling method.
Perhaps the most common use of ** in Cocoa is when using NSError objects. When a method is called that can return an NSError object on failure, the method signature would look something like this:
- (id)someMethodThatUsesObject:(id)object error:(NSError**)error;
What this means is that the calling function can pass in a pointer to an NSError object, but someMethodThatUsesObject: can change the value of error to another NSError object if it needs to, which can then be accessed by the calling method.
This is often used as a workaround for the fact that functions can only return one value.
A * in Objective-C means exactly the same as in C; and you'll usually see it (or not) in these situations:
// Method signatures:
// Here the asterisk (*) shows that you have a pointer to an NSString instance.
+ (NSString *)stringWithString:(NSString *)aString;
// Method signatures, part two:
// Here the double asterisk (**) signifies that you should pass in a pointer
// to an area of memory (NSError *) where outError can be written.
- (BOOL)writeToURL:(NSURL *) atomically:(BOOL) error:(NSError **)outError;
// Method signatures make for good examples :)
// Here the asterisk is hidden; id is a typedef for void *; and it signifies that
// a pointer to some object of an indeterminate class will be returned
- (id)init;
// And a forth example to round it all out: C strings!
// Here the asterisk signifies, you guessed it, a pointer! This time, it's a
// pointer to the first in a series of const char; terminated by a \0, also known
// as a C string. You probably won't need to work with this a lot.
- (const char *)UTF8String;
// For a bit of clarity, inside example two, the outError is used as follows:
// Here the asterisk is used to dereference outError so you can get at and write
// to the memory it points to. You'd pass it in with:
// NSError *anError;
// [aString writeToURL:myURL atomically:YES error:&anError];
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atom error:(NSError **)outError {
// do some writing, and if it went awry:
if (outError != NULL)
*outError = [NSError errorWithName:#"NSExampleErrorName"];
return NO;
}