S.J
S.J

Reputation: 3071

Need assistance understanding __block Storage Type

__block NSString *x = @"123"; //  x lives in block storage
void (^printXAndY)(NSString*) = ^(NSString *y) {
    x = [x stringByAppendingString:y];
    printf("%@ %@\n", x, y);
};
printXAndY(@"456");

Apple docs says:

The __block Storage Type You can specify that an imported variable be mutable—that is, read-write— by applying the __block storage type modifier.

If the x is mutable, isn't this x = [x stringByAppendingString:y]; wrong? and can cause memory leaks?

Upvotes: 1

Views: 137

Answers (1)

newacct
newacct

Reputation: 122439

First, you are confusing two completely unrelated things: 1) the variable being assignable (i.e. non-const), and 2) if the variable is of object pointer type, the object it points to being "mutable".

Non-__block local variables are const inside a block, which means you can't do x = something. Making the variable __block allows you to do x = something inside the block (regardless of the type of x). When x is a pointer variable, assignment to it makes it point to something else.

So-called "mutating" a "mutable" object just means you can call a method on it that somehow changes the "contents" of the object. It does not involve assigning to any pointers that may point to this object.


As to your second question, memory leaks, no, there shouldn't be any memory leaks. First of all, if you're using ARC, it's obvious that there are no leaks. Even if you are using MRC, there are no leaks. In fact, if this is MRC, none of the object pointers in this code has been retained by your function (they are not the result of retain, alloc, new, copy, etc.), so there cannot possibly be a leak.

Upvotes: 3

Related Questions