Assigning an object to a weak job in Objective-c?

According ARCto iOS, an object must have at least one link strongin order to remain in memory when there is no link strong( i.e., the reference count becomes 0 ), the object will be freed from memory, and we will no longer have access to the object.

But I get weird behavior in my code.

I assign a weaklink NSStringin the code, when I write [[NSString alloc] init];Xcode, it gives a warning.

__weak NSString *str;
str = [[NSString alloc] init];

Assigning a saved object to a weak property; the object will be released after the appointment.

Xcode warning screenshot

if I do this, Xcode does not give any warnings,

__weak NSString *str;
str = @"abcd";
NSLog(@"%@",str);

No Warning Screenshot

Output : ABCD

Output screenshots

"abcd" . str . NSString , "abcd" ?

+4
2

str = @"abcd", , , __weak.

, @"abcd" . . retain release . , . , __weak str nil, . abcd.

, clang , ( - , @[a, b, c]). . :

static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
                                     Expr *RHS, bool isProperty) {
  // Check if RHS is an Objective-C object literal, which also can get
  // immediately zapped in a weak reference.  Note that we explicitly
  // allow ObjCStringLiterals, since those are designed to never really die.
  RHS = RHS->IgnoreParenImpCasts();

  // This enum needs to match with the 'select' in
  // warn_objc_arc_literal_assign (off-by-1).
  Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
    return false;

  S.Diag(Loc, diag::warn_arc_literal_assign)
    << (unsigned) Kind
    << (isProperty ? 0 : 1)
    << RHS->getSourceRange();

  return true;
}

, NSArray , :

array symbol assignment warning

... , str = [[NSString alloc] init], , [[NSString alloc] init] - , .

, [[NSString alloc] init] , str nil. , -[NSString init] . .

    __weak NSString *str;
    str = [[NSString alloc] init];
    NSLog(@"%ld %p [%@]", CFGetRetainCount((__bridge CFTypeRef)str), str, str);

:

2018-01-24 01:00:22.963109-0600 test[3668:166594] 1152921504606846975 0x7fffe55b19c0 []

, 1152921504606846975 - - , .

+5
#define TLog(_var) ({ NSString *name = @#_var; NSLog(@"%@: %@ -> %p: %@ retainCount:%ld", name, [_var class], _var, _var, CFGetRetainCount((__bridge CFTypeRef)(_var))); })

__weak NSString *str;
str = @"abcd";
NSLog(@"%@",str
      );
TLog(str);

, [str class] NSCFConstantString, Count is 1152921504606846975.

keepCount Objective-C. preserveCount 1152921504606846975, "unlimited retainCount", , .

__NSCFConstantString object preserveCount 1152921504606846975, , __NSCFConstantString , __weak. NSString, *str = @"abcd";, , , .

0

Source: https://habr.com/ru/post/1692616/


All Articles