Objective-C blocks and capturing self - objective-c

Every thread I've come across with keywords 'block' and 'self' seem to be in regards to retain cycles. But that's not the issue here...
My question is: Why are changes made to properties of self outside the block visible in the block? I thought values were meant to be 'captured'? That is, what the block references is a copy of the original object?
Here's a bit of code to illustrate my dilemma:
int a = 1;
self.someProperty.name = #"Foo";
[self.someProperty someMethodWithCompletionHandler:^() {
NSLog(#"%d", a);
NSLog(#"%#", self.someProperty.name);
}];
a = 2;
self.someProperty.name = #"Bar";
The output I get is:
1
Bar

Values are captured, that's why a is 1 inside the block.
But your string is an object. The pointer (just an address really) is captured but the value of the string it is pointing to has changed. That's why you see "Bar".

C, and by extension, Objective-C uses by-value semantics. That is, when passing parameters to a function, a copy of the variable's value is passed to the callee. The way to allow the callee to change the original variable that would have been copied is to pass a pointer. The callee now has a way to directly access the memory location referred to by the original variable.
int a = 1; // a is stored at memory location 0xABCD
f(a); // The value of a (1) is passed to f(). This copy is at 0xCDEF.
void f(int a) {
// The value at 0xCDEF is now 10, but 0xABCD (the "original") is untouched.
a = 10;
}
g(&a); // The address of "a" is passed. This is the value 0xABCD.
void g(int *a) {
// This dereferences the pointer and changes the value at that location to 10.
// As the value of the pointer is the address of "a", the original variable "a"
// now has the new value of 10.
*a = 10;
}
Blocks in Objective-C work the same way. The captured values are the same sort that would have been passed as parameters to a function. This means that passing non-pointers will not allow the original variable to change, while passing pointers will allow the memory at those locations to be altered. As objects can only be accessed through pointers, every object variable is a pointer. This allows the block to manipulate the object the same way g() in the example above can manipulate the "original" a variable.

Related

Keeping objectiveC object valid outside the scope of a function

I'm a bit confused about ARC behaviour when setting variable that is an input pointer, and is expected to remain valid outside function scope.
considering the following example that uses openDirectory framework.
#interface bbb
-(bool)doSomethingWithADRecord:
-(void)obtainADRecord(NSString*)user
-(NSString*)getADrecord:(ODAttributeType)attr fromRecord:(ODRecord*)record;
#end
#interface bbb {
ODRecord *_myRecord;
}
#end
#implementation bbb
-(void)doSomethingWithADRecord:
{
// here we access _myRecord and expect it to be valid.
}
-(bool)obtainADRecord:(NSString*)user
{
...
// here I call the method that will set the member _myRecord from type ODRecord*
// whose scope related to the lifespan of the containing class (bbb)
[self getADrecord:attr toRecord:_myRecord];
}
// the following function should set the variable record to be used by the caller.
-(NSString*)getADrecord:(ODAttributeType)attr fromRecord:(ODRecord*)record {
...
// here a set an ODQuery object.
ODQuery *query = [[ODQuery alloc] initWithNode ...
// queryResults is an array of items from type ODQuery*
NSArray* queryResults = [query resultsAllowingPartial:NO error:&err];
for(ODRecord *item in queryResults) {
if (/*some logic*/)
{
//option 1: just regular set operator, expecting the ARC will do the retain itself
record = item;
//option 2: explicits take a reference on that item.
record = [[item retain] autorelease];
return #"found item";
}
}
}
#end
To Clarify my question, I seek to know which one of the 2 options I stated above is the correct one , in terms of passing the reference to record and eventually to _myRecord, so it will store the correct value even after the temporal list of queryResults will be cleaned.
Notice that in both options I simply setting the pointer value without initiate new object from type ODquery and copying the data to this new object.
thanks !
I'd like to know whether simply doing record = item will be enough for the data pointed by this object to last beyond the scope of the function getADrecord
You are misunderstanding how parameters work; a parameter, such as record, is essentially a local variable which is initialised to the value passed in the call.
Therefore any assignment of an object reference to record will have zero effect on the lifetime of the referenced object outside of the scope of getADrecord as record is local to the function.
To return a value of type T via a parameter the type of the parameter must be of type "pointer to a variable of type T". An example with a simple value type:
- (void) add:(int)value // an int value
to:(int *)ptrToVariable // a pointer to an int variable
{
// note the need to indirect (`*`) through pointer stored in
// `ptrToVariable` to access the pointed at variable
*ptrToVariable = *ptrToVariable + value;
}
int x = 31;
[self add:11 to:&x]; // &x creates a pointer to the variable x
// x = 42 after call
Now you don't want to return a simple value type but a value which is a reference to an object and you wish ARC to manage the lifetime correctly. This is a little more complicated.
Under ARC a variable which holds a reference to an object has both a type and an ownership attribute; this attribute informs ARC how to handle storing references in the variable. The common ownership attributes are __strong and __weak, without an explicit attribute __strong is assumed. So your instance variable declaration is shorthand for:
ODRecord __strong *_myRecord;
This declaration means that for any reference to an ODRecord stored into _myRecord ARC will keep the referenced ODRecord alive at least as long as _myRecord exists and the reference is not overwritten by a different reference or nil. It is "at least as long" as the same reference could be stored elsewhere and these will also effect the lifetime.
Almost there! To return a reference to an ODRecord via a parameter the type of the parameter must be "pointer to a variable of type strong reference to ODRecord, i.e.:
- (NSString *)getADrecord:(ODAttributeType)attr
fromRecord:(ODRecord * __strong *)record
now an assignment such as:
*record = item;
will result in an assignment to the pointed-at variable and as that variable is of type ODRecord __strong * ARC will ensure the referenced ODRecord will live at least as long as a reference to it is stored in the pointed-at variable.
Your call to this method must pass a pointer to your variable:
[self getADrecord:attr toRecord:&_myRecord];
Notes:
"out" parameters are not often used in Objective-C with the notable exception of error returns – these are of type NSError * _autoreleasing * and Apple names this usage as "call-by-writeback".
For a deeper explanation of ARC and returning values via parameters see Handling Pointer-to-Pointer Ownership issues in ARC and NSError and __autoreleasing
Important:
As pointed out by #matt in the comments your code contains retain and autorelease calls which are forbidden in ARC and therefore if your code is compiling you DO NOT have ARC enabled. For new projects ARC will be enabled, for existing projects you may need to enable it your project's Build Settings, the setting is called "Objective-C Automatic Reference Counting".
A call to "autorelease" means the object has an additional retain count that will go away when you leave the current autorelease scope, which is typically when the current event is finished.
record = item is obviously not enough, because record's retain count goes away when records leaves scope, that is when the function returns.
But what you do - calling autorelease for each item makes sure that all the items remain allocated for a while, not just "record".

Why does Block use struct __Block_byref_object_0 instead of a single pointer to capture a variable decorated with "__block"

Here is my source code in file main.m
__block NSInteger blockInteger = 123;
static NSInteger staticInteger = 123;
void (^testBlock)(void) = ^() {
blockInteger++;
staticInteger++;
NSLog(#"%ld", blockInteger);
NSLog(#"%ld", staticInteger);
};
testBlock();
When I used clang command "clang -rewrite-objc main.m", I got this
struct __Block_byref_blockInteger_0 {
void *__isa;
__Block_byref_blockInteger_0 *__forwarding;
int __flags;
int __size;
NSInteger blockInteger;
};
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
NSInteger *staticInteger;
__Block_byref_blockInteger_0 *blockInteger; // by ref
...
};
I am wondering why block use __Block_byref_blockInteger_0 to capture blockInteger since it use a NSInteger pointer to capture a static variable . What does __Block_byref_blockInteger_0 exactly do? What are the advantages of this struct by comparing with a pointer?
The compiler is creating a number of structures to help the block refer to its "enclosed" values. (Remember that a block makes a copy of, or "encloses", all of the values that are outside the block, which is why blocks are also called "closures".)
So the first structure (__Block_byref_blockInteger_0) is creating an object to encapsulate the blockInteger automatic. This is because automatic variables disappear at the end of the function, but blocks must be able to refer to them long afterwards.
The second structure encapsulates all of the values (including __Block_byref_blockInteger_0) that are being "captured" by the block. This give the block a single reference to all of its enclosed values, copied when the block was created.
Now the NSInteger *staticInteger instance value is a bit of an odd duck, since the address of the global staticInteger can't change. But that's a pretty minor difference as it's still just a copy of an address; whether that address can change is immaterial.
I suspect it's because of name scope; a static declared inside a function has a symbol scope limited to that function. And if you look at the compiler output, you'll see that every block you declare creates an invisible static function to contain its code. Since that second static function wouldn't normally be able to reference a static declared within another function, making a copy of the static's address is the only way for the block function to access it.

__block for method parameters in Objective C?

So thanks to this post, I'm familiar with the __block keyword.
It basically means to NOT copy the instance, but rather just passing its original reference.
The benefits I see for doing that are:
Any modification made to the instance inside the block will reflect in the original instance.
Avoiding the "waste" of copying the instance we're gonna use inside the block.
I am curious, though, how much should we really bother with this declaration, for example, if I have this method that receives a callback block as a parameter:
-(void)doSomethingWithCallback:(MyTypeOfCallback)callback;
and let's say this method calls another method with a callback as a parameter. Is it then worthwhile to __block the original callback parameter if we want to call it inside the next method:
-(void)doSomethingWithCallback:(MyTypeOfCallback)callback
{
__block MyTypeOfCallback blockCallback = callback;
[self doAnotherThingWithBlock:^(BOOL result) {
if (result)
blockCallback();
}];
}
or should I simply call the original block parameter inside the next method?
-(void)doSomethingWithCallback:(MyTypeOfCallback)callback
{
[self doAnotherThingWithBlock:^(BOOL result) {
if (result)
callback();
}];
}
I'm asking because it makes sense to include the __block option, but then again I find myself doing it in too many places and it's starting to take many code lines.
BTW, this also goes for every any other type of parameter, not only blocks.
It's basically telling the compiler to NOT copy the instance
No. __block has nothing to do with "instances". __block is a storage qualifier for variables.
__block on a variable means that the same copy of the variable will be shared between the original scope any any blocks that capture it (as opposed to each block getting a separate copy of the variable when it captures non-__block variables).
In your case, you have a variable of type MyTypeOfCallback, a (I'm guessing) pointer-to-block type. In the first piece of code, you make it __block, so there is a single pointer variable whose state is shared between the function scope and the block (which captures it). If either scope assigns to the pointer variable, the change would be visible in the other scope.
In the second piece of code, you make it non-__block, and when the block literal is executed, it copies the value of that pointer at that moment into a separate pointer variable in its own structure, so that you have two copies of the pointer. If you afterwards assign to the pointer variable in the function scope, the change would not be visible to the block, since it has its own copy.
In this case, there is no difference between the two, because you never assign to the pointer variable in question after initialization. It is basically a constant variable, and one copy or two copies makes no difference.
-(void)doSomethingWithCallback:(MyTypeOfCallback)callback
{
__block MyTypeOfCallback blockCallback = callback;
[self doAnotherThingWithBlock:^(BOOL result) {
if (result)
blockCallback();
}];
}
You can call callback from in block so
-(void)doSomethingWithCallback:(void(^)(void))callback
{
__block typeof(callback)blockCallback = callback;
[self doAnotherThingWithBlock:^(BOOL result) {
if (result)
blockCallback();
}];
}

How do I write to an NSObject from within a C function that doesn't see Obj-C variables?

I'm trying to get some code going that lets me display raw trackpad data from my macbook pro, like the app FingerMgmt. Unfortunately, no one seems to have the source for FingerMgmt. I did find some other source code that kind of works, however. I was able to NSLog the data I wanted to see like this:
int callback(int device, Finger *data, int nFingers, double timestamp, int frame) {
for (int i=0; i<nFingers; i++) {
Finger *f = &data[i];
NSLog(#"Frame %7d: Angle %6.2f, ellipse %6.3f x%6.3f; "
"position (%6.3f,%6.3f) vel (%6.3f,%6.3f) "
"ID %d, state %d [%d %d?] size %6.3f, %6.3f?\n",
f->frame,
f->angle * 90 / atan2(1,0),
f->majorAxis,
f->minorAxis,
f->normalized.pos.x,
f->normalized.pos.y,
f->normalized.vel.x,
f->normalized.vel.y,
f->identifier, f->state, f->foo3, f->foo4,
f->size, f->unk2);
//todo-get data from raw C to obj-C variable
}
return 0;
}
But whenever I try to store any of the data to an Obj-c string or variable, the C code does not see the variable as having been declared. Because of this, I cannot write to any text fields or graphical displays in Obj-C, and I cannot store the data to a variable that Obj-c can access.
Basically, I need a way to write to an Obj-C variable or object from within the callback.
On a side note, I had a very similar problem with an iPhone app a while back, and I ended up fixing it by somehow declaring the app delegate within the C code and writing to or reading from the variable like this-
me.delegate=(id <UIApplicationDelegate,UITabBarControllerDelegate>)[[UIApplication sharedApplication] delegate];//allows access to the delegate within C function
me.delegate.number0=5;//writes to this variable in the delegate
For some reason, I can not seem to adapt this to my current situation. I always get the error that "me" is undeclared.
A Objective-C method can access instance variables because it is automagically passed a hidden parameter with the public name self - any reference to an instance variable, say fred, is translated by the compiler into a field reference, say self->fred (and a similar translation for property references).
For your C function callback to access the fields of any object (or call an object's methods) you need to pass the function a reference to the object. Two simple ways:
Add an argument to the function. Many C callback protocols include a general "user defined" values which is passed around as void *, if you are calling one of these pass your object reference as this value and cast it within the C function back to the correct Objective-C type.
Pass the object via a global (or file static) variable, e.g. static NSSomeType *objectForCallback;. This method works when you're stuck with an existing C callback protocol which doesn't support a user defined value. However it is not thread or re-entrant safe as you are sharing a single static variable.
In both cases make sure the objected is retain'ed if you're not using garbage collection.
In response to comment
Case 1: You will see C functions declared which (a) take a callback function and (b) a user-defined value to pass to that function on every call. For example:
typedef T ...;
T findMatching(T *buffer, // an array of T to search
size_t count, // number of items in array
int (*matcher)(T item, void *user), // user function for match, 1st arg is item, 2nd user-supplied value
void *userValue); // user-supplied value to pass to matcher
If you are faced with C function like this you can pass a (retain'ed if needed) Objective-C object as userValue and cast it back to its Objective-C type inside matcher. For example:
int myMatcher(T item, void *user)
{
NSMutableDictionary *myDictionary = (NSMutableDictionary *)user;
...
}
- (void) someMethod
{
NSMutableDictionary *sharedWithC = ...;
...
T found = findMatching(buffer, count, myMatcher, (void *)sharedWithC);
...
}
Case 2: Objective-C is (a superset of) C. You declare a global just as you would in C. For example (little checking, not thread safe):
static NSMutableDictionary *myGlobalDictionary = nil; // "static" makes the variable only visible to code in the same file
- (void) setupTheSharedDictionary
{
myGlobalDictionary = [[[NSMutableDictionary alloc] init] retain];
}
- (void) releaseTheSharedDictionary
{
if(myGlobalDictionary != nil)
{
[myGlobalDictionary release];
myGlobalDictionary = nil;
}
}
In response to second comment
I'm guessing you are trying to use some third party (Google?) code. That code defines a callback protocol - a C function type. You cannot just redefine that C function type adding an extra argument and expect the third party code to magically cope!
So unless you intend to change the C you can use the second approach - store the reference to Objective-C object in a global. In your case this will be something like:
static MT2AppDelegate *sharedWithCAppDelegateReference;
int callback(...)
{
...
[sharedWithCAppDelegateReference->L1 setStringValue:#"Hellofff"];
...
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
sharedWithCAppDelegateReference = self; // store so C can pick it up
...
MTRegisterContactFrameCallback(dev, callback);
...
}
But remember this is not thread or re-entrant safe - you are effectively passing a function parameter via a global variable. If you need it to be thread/re-entrant safe you need to get a bit more involved.

Passing arguments by value or by reference in objective C

I'm kind of new with objective c and I'm trying to pass an argument by reference but is behaving like it were a value. Do you know why this doesn't work?
This is the function:
- (void) checkRedColorText:(UILabel *)labelToChange {
NSComparisonResult startLaterThanEnd = [startDate compare:endDate];
if (startLaterThanEnd == NSOrderedDescending){
labelToChange.textColor = [UIColor redColor];
}
else{
labelToChange.textColor = [UIColor blackColor];
}
}
And this is the call:
UILabel *startHourLabel; // This is properly initialized in other part of the code
[self checkRedColorText:startHourLabel];
Thanks for your help
Objective-C only support passing parameters by value. The problem here has probably been fixed already (Since this question is more than a year old) but I need to clarify some things regarding arguments and Objective-C.
Objective-C is a strict superset of C which means that everything C does, Obj-C does it too.
By having a quick look at Wikipedia, you can see that Function parameters are always passed by value
Objective-C is no different. What's happening here is that whenever we are passing an object to a function (In this case a UILabel *), we pass the value contained at the pointer's address.
Whatever you do, it will always be the value of what you are passing. If you want to pass the value of the reference you would have to pass it a **object (Like often seen when passing NSError).
This is the same thing with scalars, they are passed by value, hence you can modify the value of the variable you received in your method and that won't change the value of the original variable that you passed to the function.
Here's an example to ease the understanding:
- (void)parentFunction {
int i = 0;
[self modifyValueOfPassedArgument:i];
//i == 0 still!
}
- (void)modifyValueOfPassedArgument:(NSInteger)j {
//j == 0! but j is a copied variable. It is _NOT_ i
j = 23;
//j now == 23, but this hasn't changed the value of i.
}
If you wanted to be able to modify i, you would have to pass the value of the reference by doing the following:
- (void)parentFunction {
int i = 0; //Stack allocated. Kept it that way for sake of simplicity
[self modifyValueOfPassedReference:&i];
//i == 23!
}
- (void)modifyValueOfPassedReference:(NSInteger *)j {
//j == 0, and this points to i! We can modify i from here.
*j = 23;
//j now == 23, and i also == 23!
}
Objective-C, like Java, only has pass-by-value. Like Java, objects are always accessed through pointers. "objects" are never values directly, hence you never assign or pass an object. You are passing an object pointer by value. But that does not seem to be the issue -- you are trying to modify the object pointed to by the pointer, which is perfectly allowed and has nothing to do with pass-by-value vs. pass-by-reference. I don't see any problem with your code.
In objective-c, there is no way to pass objects by value (unless you explicitly copy it, but that's another story). Poke around your code -- are you sure checkRedColorText: is called? What about [startDate compare:endDate], does it ever not equal NSOrderedDescending? Is labelToChange nil?
Did you edit out code between this line
UILabel *startHourLabel;
and this line?
[self checkRedColorText:startHourLabel];
If not, the problem is that you're re-declaring your startHourLabel variable, so you're losing any sort of initialization that was there previously. You should be getting a compiler error here.
Here are the possibilities for why this doesn't work:
the label you pass in to checkRedColorText is not the one you think it is.
the comparison result is always coming out the same way.
... actually, there is no 3.
You claim you initialised startHourLabel elsewhere, but, if it is a label from a nib file, you should not be initialising it at all. It should be declared as an IBOutlet and connected to the label in the nib with interface builder.
If it is not a label in the nib i.e. you are deliberately creating it programmatically, you need to check the address of the label you initialise and check the address of the label passed in to checkRedColorText. Either NSLog its address at initialisation and in checkRedColorText or inspect it with the debugger.