I have a category class for NSString.
#implementation NSString (URLEncode)
- (NSString *)URLEncodedString
{
__autoreleasing NSString *encodedString;
NSString *originalString = (NSString *)self;
encodedString = (__bridge_transfer NSString * )
CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)originalString,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
return encodedString;
}
Am I using the correct bridge transfers for ARC and the new LLVM?
The original code:
- (NSString *)URLEncodedString
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
return [encodedString autorelease];
}
As mentioned in the comments, I think it's fine to talk about ARC and the contents of Automatic Reference Counting here.
__autoreleasing is not meant to be used like that. It's used for passing indirect object references (NSError**, etc). See 4.3.4 Passing to an out parameter by writeback.
According to 3.2.4 Bridged casts, the __bridge_transfer is correct as the CFURLCreateStringByAddingPercentEscapes function returns a retained object (it has "create" in its name). You want ARC to take ownership of the returned object and insert a release (or autorelease in this case) to balance this out.
The __bridge cast for originalstring is correct too, you don't want ARC to do anything special about it.
This is a correct, not leaking version.
As you say in the comments: __bridge_transfer transfer the ownership to NSObject (NSString) and assume that the object is retained by CF Framework (the method CFURLCreateStringByAddingPercentEscapes return a retained object so this is what we need)
than on the self object we don't want to perform any memory management. Hope it helps
Fra
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
-(NSString *) urlEncoded
{
CFStringRef encodedCfStringRef = CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)self,NULL,(CFStringRef)#"!*'\"();#+$,%#[]% ",kCFStringEncodingUTF8 );
NSString *endcodedString = (NSString *)CFBridgingRelease(encodedCfStringRef);
return endcodedString;
}
No __autoreleasing necessary. The correct ARC syntax is simply:
- (NSString *)URLEncodedString
{
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8));
}
Related
I would like to put a pointer to an NSString pointer into an NSDictionary, and naturally, get it back out again. But I can't figure out the syntax.
I think is is something like
NSString* myString = #"Hi";
NSString**myStringPointer = myString;
NSDictionary* dictionary = #{#"pointer":myStringPointer};
But that is clearly not correct.
I am trying to change what string an NSString points to inside a selector.
-(void) updateString:(NSString*) aString {
aString = #"Hello World"; //
}
-(void) testUpdateString {
NSString *textString = #"TEST";
[self updateString:testString];
// testString still is #"TEST";
}
Thank you.
You can only put (pointers to) things that inherit from NSObject in an NSDictionary; a pointer to (a pointer to) an NSString isn't such an object. You can wrap it in an NSValue to store it in a dictionary.
NSDictionary *dictionary = #{ #"pointer": [NSValue valueWithPointer:myStringPointer], };
While it's worth being aware of the general idea of wrapping things that couldn't otherwise be put into an NSDictionary, NSArray, etc., in NSValue for this purpose, I can't think of a good reason to store an NSString ** in an NSDictionary, so it might be better to look at why you're trying to do that and whether there's a better way to achieve your larger goal.
You don't need a dictionary here, you can pass the object by reference to the updating
method:
-(void) updateString:(NSString **) aString {
*aString = #"Hello World";
}
-(void) testUpdateString {
NSString *testString = #"TEST";
[self updateString:&testString];
}
(If you are curious what actually happens behind the scenes, look up
__autoreleasing in the "Transitioning to ARC Release Notes".)
I am trying to understand the correct way of getting an NSString from a CFStringRef in ARC?
Same for going the opposite direction, CFStringRef to NSString in ARC?
What is the correct way to do this without creating memory leaks?
Typically
NSString *yourFriendlyNSString = (__bridge NSString *)yourFriendlyCFString;
and
CFStringRef yourFriendlyCFString = (__bridge CFStringRef)yourFriendlyNSString;
Now, if you want to know why the __bridge keyword is there, you can refer to the Apple documentation. There you will find:
__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.
__bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you.
You are responsible for calling CFRelease or a related function to relinquish ownership of the object.
__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.
ARC is responsible for relinquishing ownership of the object.
Which means that in the above cases you are casting the object without changing the ownership.
This implies that in neither case you will be in charge of handling the memory of the strings.
There may also be the case in which you want to transfer the ownership for some reason.
For instance consider the following snippet
- (void)sayHi {
CFStringRef str = CFStringCreateWithCString(NULL, "Hello World!", kCFStringEncodingMacRoman);
NSString * aNSString = (__bridge NSString *)str;
NSLog(#"%#", aNSString);
CFRelease(str); //you have to release the string because you created it with a 'Create' CF function
}
in such a case you may want to save a CFRelease by transferring the ownership when casting.
- (void)sayHi {
CFStringRef str = CFStringCreateWithCString(NULL, "Hello World!", kCFStringEncodingMacRoman);
NSString * aNSString = (__bridge_transfer NSString *)str;
// or alternatively
NSString * aNSString = (NSString *)CFBridgingRelease(str);
NSLog(#"%#", aNSString);
}
The ownership of str has been transferred, so now ARC will kick in and release the memory for you.
On the other way around you can cast a NSString * to a CFString using a __bridge_retained cast, so that you will own the object and you'll have to explicitly release it by using CFRelease.
To wrap it up you can have
NSString → CFString
// Don't transfer ownership. You won't have to call `CFRelease`
CFStringRef str = (__bridge CFStringRef)string;
// Transfer ownership (i.e. get ARC out of the way). The object is now yours and you must call `CFRelease` when you're done with it
CFStringRef str = (__bridge_retained CFStringRef)string // you will have to call `CFRelease`
CFString → NSString
// Don't transfer ownership. ARC stays out of the way, and you must call `CFRelease` on `str` if appropriate (depending on how the `CFString` was created)
NSString *string = (__bridge NSString *)str;
// Transfer ownership to ARC. ARC kicks in and it's now in charge of releasing the string object. You won't have to explicitly call `CFRelease` on `str`
NSString *string = (__bridge_transfer NSString *)str;
Why am I getting memory leaking while analyzing using XCode?
NSString *email = [defaults objectForKey:#"email"];
NSString *encodeEmail = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
NSString *urlp1=#"/xyz/xx/";
NSString *fullUrl=[urlp1 stringByAppendingString: [NSString stringWithFormat:#"%#/following", encodeEmail]];
From transitioning to ARC release notes
__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.
It means encodeEmail doesn't have the ownership of the allocated memory, and so it won't be released by ARC.
I think you should use __bridge_transfer
__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC. ARC is responsible
for relinquishing ownership of the object.
NSString *encodeEmail = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
You are using CFURLCreateStringByAddingPercentEscapes which you have to release since you own it(Check the 'create' in the name)
You can try it as,
CFStringRef stringRef = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
encodeEmail = [NSString stringWithFormat:#"%#",(NSString *)stringRef];
CFRelease(stringRef);
Update:
If you are using ARC, you can also use __bridge_transfer for transferring ownership from created CFObjects to NSObjects. You just have to use it as NSString *encodeEmail = (__bridge_transfer NSString *)...
Because you will leak an object. To be specific the the CFString returned by the method CFURLCreateStringByAddingPercentEscapes that method, which includes the keyword "create", returns a retained item. You must either manually release it, or tell ARC to handle it for you using:
NSString *encodeEmail = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
Note the __bridge_transfer that lets ARC handle the memory management for you, and it will eliminate your warning.
I have this question here (as well other quesrtions on SO), and the Apple docs about Objective-C collections and fast enumeration. What is not made clear is if an NSArray populated with different types, and a loop is created like:
for ( NSString *string in myArray )
NSLog( #"%#\n", string );
What exactly happens here? Will the loop skip over anything that is not an NSString? For example, if (for the sake of argument) a UIView is in the array, what would happen when the loop encounters that item?
Why would you want to do that? I think that would cause buggy and unintended behavior. If your array is populated with different elements, use this instead:
for (id object in myArray) {
// Check what kind of class it is
if ([object isKindOfClass:[UIView class]]) {
// Do something
}
else {
// Handle accordingly
}
}
What you are doing in your example is effectively the same as,
for (id object in myArray) {
NSString *string = (NSString *)object;
NSLog(#"%#\n", string);
}
Just because you cast object as (NSString *) doesn't mean string will actually be pointing to an NSString object. Calling NSLog() in this way will call the - (NSString *)description method according to the NSObject protocol, which the class being referenced inside the array may or may not conform to. If it conforms, it will print that. Otherwise, it will crash.
You have to understand that a pointer in obj-c has no type information. Even if you write NSString*, it's only a compilation check. During runtime, everything is just an id.
Obj-c runtime never checks whether objects are of the given class. You can put NSNumbers into NSString pointers without problems. An error appears only when you try to call a method (send a message) which is not defined on the object.
How does fast enumeration work? It's exactly the same as:
for (NSUInteger i = 0; i < myArray.count; i++) {
NSString* string = [myArray objectAtIndex:i];
[...]
}
It's just faster because it operates on lower level.
I just tried a quick example... Here is my code.
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];
NSNumber *number = [NSNumber numberWithInteger:6];
[array addObject:number];
[array addObject:#"Second"];
Now if I simply log the object, no problem. The NSNumber instance is being cast as an NSString, but both methods respond to -description, so its not a problem.
for (NSString *string in array)
{
NSLog(#"%#", string);
}
However, if I attempt to log -length on NSString...
for (NSString *string in array)
{
NSLog(#"%i", string.length);
}
... it throws an NSInvalidArgumentException because NSNumber doesn't respond to the -length selector. Long story short, Objective-C gives you a lot of rope. Don't hang yourself with it.
Interesting question. The most generic syntax for fast enumeration is
for ( NSObject *obj in myArray )
NSLog( #"%#\n", obj );
I believe that by doing
for ( NSString *string in myArray )
NSLog( #"%#\n", string );
instead, you are simply casting each object as an NSString. That is, I believe the above is equivalent to
for ( NSObject *obj in myArray ) {
NSString *string = obj;
NSLog( #"%#\n", string );
}
I could not find precise mention of this in Apple's documentation for Fast Enumeration, but you can check it on an example and see what happens.
Since all NSObject's respond to isKindOfClass, you could still keep the casting to a minimum:
for(NSString *string in myArray) {
if (![string isKindOfClass:[NSString class]])
continue;
// proceed, knowing you have a valid NSString *
// ...
}
Can anyone please review the following method and tell me if it is necessary to release the enumerator for the dictionary keys after using it?
I'm new to objective c and not always sure, when to release variables returned from the SDK methods. I suppose the keyEnumerator method returns an autoreleased instance so I don't have to care about it when I'm finished with it. Right?
Hmm.. maybe anything else wrong in this method? ;)
#import "NSDictionaryURLEncoding.h"
#import <Foundation/NSURL.h>
#implementation NSDictionary(URLEncoding)
-(NSString *)urlEncoded
{
NSEnumerator *keyEnum = [self keyEnumerator];
NSString *currKey;
NSString *currObject;
NSMutableString *result = [NSMutableString stringWithCapacity: 64];
while ((currKey = [keyEnum nextObject]) != nil)
{
if ([result length] > 0)
{
[result appendString: #"&"];
}
currObject = [[self objectForKey: currKey] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
currKey = [currKey stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[result appendString: [NSString stringWithFormat:#"%#=%#", currKey, currObject]];
}
return result;
}
#end
You must never release objects for which you did not call the alloc method if you also didn't retain them. See the Memory Management Programming Guide for Cocoa.
Also, if you're programming for the iPhone OS or if you are targetting Mac OS X 10.5 or later, I suggest you use the for(... in ...) language construct to enumerate through your dictionary. It's much faster than using enumerators.
for(NSString* currKey in self)
{
NSString* currObject = [self objectForKey:currKey];
// the rest of your loop code
}
You should read the Fast Enumeration section of the Objective-C Programming Language Reference.
I also suggest, as a friendly advice, that you don't extend NSDictionary or create a category on it unless you really, really need it.