Haagenti
Haagenti

Reputation: 8144

iOS why does this property needs to be strong

I have a property which I thought could be weak. But it doesn't display unless it is set to strong.

This:

- (void) setTimeAndLocation:(Message *)activity{
    __weak NSString *time = [[[activity getPropertyByPath:@"StartTime"] value] substringWithRange:NSMakeRange(0, 5)];
    NSLog(@"Time: %@", time); // null

    __strong NSString *time = [[[activity getPropertyByPath:@"StartTime"] value] substringWithRange:NSMakeRange(0, 5)];
    NSLog(@"Time: %@", time); // works, 20:30

    __weak NSString *time = [[activity getPropertyByPath:@"StartTime"] value];
    NSLog(@"Time: %@", time); // works, 20:30:00
}

Is this because substring creates a new string or something like that? I know I don't have to add the __weak or __strong but this is for me very helpful to understand what everything does

Upvotes: 0

Views: 73

Answers (1)

Ricardo Sanchez-Saez
Ricardo Sanchez-Saez

Reputation: 9566

time is a local variable, not a property.

Generally, all local variables are __strong (which is the default when you omit the modifier) because they are automatically disposed when they go out of scope.

You never declare a local variable __weak for a newly created object, because the object will be destroyed as soon as it is created. I suspect that substringWithRange: creates a new object, as you mention.

The fact that the second one works is misleading. When you declare a local variable __weak you have no guarantees that it will be available unless you know you are accessing an object that is strongly retained elsewhere. The variable should be __strong (no modifier) in both cases.


__weak is used when you want to create a weak local variable of a previously created object that is strongly referenced elsewhere. Typically, you use __weak variables if you wish to avoid retain cycles inside retained blocks.

Upvotes: 4

Related Questions