Hold showing MaxInt

When I try to print the saveCount object, I get 2147483647. Why am I getting this result? It should be 1, shouldn't it?

NSString *myStr = [NSString new]; NSUInteger retCount = [myStr retainCount]; NSLog(@"refCount = %u", retCount); 

2011-09-08 17: 59: 18.759 Test [51972: 207] refCount = 2147483647

I am using Xcode Version 4.1. Trial compilers GCC 4.2 and LLVM GCC 4.2 - the same result. Garbage collection has been set to unsupported.

+6
source share
4 answers

NSString is a little special when it comes to memory management. String literals (something like @"foo" ) are efficient singletones, each line with the same content is the same object, because it cannot be changed in any way. Since [NSString new] always creates an empty string that cannot be changed, you will always get the same instance that cannot be released (thus a high retainCount ).

Try this snippet:

 NSString *string1 = [NSString new]; NSString *string2 = [NSString new]; NSLog(@"Memory address of string1: %p", string1); NSLog(@"Memory address of string2: %p", string2); 

You will see that both lines have the same memory address and therefore the same object.

+15
source

This does not give a direct answer to your question, but saveCount is actually not that useful and should not be used for testing. See this SO post for more details. When to use -retainCount?

+12
source

While NSString is an odd case (there are others in the structure), you may also encounter this in other clans - this is one way to create a single object.

Singleton exists only once in the application, and it is important that it is never released! Therefore, he will overwrite some NSObject methods, including (but not limited to):

 - (id)release { // Ignore the release! return self; } - (NSUInteger)retainCount { // We are never going to be released return UINT_MAX; } 

This object can never be released and tells the framework that it has a singleton, having a ridiculously high retention rate.

Checkout this link for more information on singleton properties.

+4
source

I have seen this several times regarding NSStrings, saveCount returns the maximum score instead of the actual one when you try to look at keepCounts of rows in this way.

Try it;

 NSString *myStr = [[NSString alloc] init]; NSUInteger retCount = [myStr retainCount]; NSLog(@"refCount = %u", retCount); 

Edit: Refurbished NSUInteger

+1
source

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


All Articles