Append a NSString as the first line of another NSString - objective-c

I have two NSString, A and B.
I would that A becomes B\nA.
How can I do?
If in a method I use
NSString *string_B = [[NSString alloc] initWithString:#"something_from_a_DB"];
NSString *string_A = [[NSString alloc] initWithString:#"something_from_a_DB"];
if (aTrueCondition) {
string_C = [NSString stringWithFormat:#"%#\n%#", string_B, string_A];
} else {
string_C = string_A;
}
is string_C = string_A; a memory leak or is it good?
I added [string_A release], as string_C is a retained property. Now it works.

This is the way to put them together:
NSString *newString = [NSString stringWithFormat:#"%#\n%#", stringB, stringA];
The second part is “A becoming newString”. This is hard to do, as regular strings are immutable in Cocoa. The best thing you can do is throw out the old A and point A to the new string:
NSString *strA = #"foo";
NSString *strB = #"bar";
strA = [NSString stringWith…];
Just be careful not to leak A:
NSString *strA = [[NSString alloc] initWithString:#"foo"];
strA = [NSString stringWith…]; // this is a leak

NSString *str=[NSString stringWithFormat:#"%#\n%#",B,A];
use this.

NSString *stringA = [NSString stringWithFormat:#"%#\n%#", stringB, stringA];

Related

NSString addition what does this Objective-c code do?

Ran across this NSString Addition and I hav no idea what it does or is used for?
NSString *NSStringWithFormat(NSString *formatString, ...) {
va_list args;
va_start(args, formatString);
NSString *string = [[NSString alloc] initWithFormat:formatString arguments:args];
va_end(args);
#if defined(__has_feature) && __has_feature(objc_arc)
return string;
#else
return [string autorelease];
#endif
}
It's a C function that lets you do this:
NSString *str = NSStringWithFormat(#"This is a number: %d", someIntValue);
instead of this:
// No ARC
NSString *str = [NSString stringWithFormat:#"This is a number: %d", someIntValue];
or
// With ARC
NSString *str = [[NSString alloc] initWithFormat:#"This is a number: %d", someIntValue];
Seems kind of pointless to me since with or without ARC you can use the "No ARC" code. This C function only saves a few characters.

Initialize the empty string in ObjectC?

Someone use the following to initialize the NSstring
NSString *astring = [[NSString alloc] init];
I am wondering why not just use
NSString *atring = nil or NSString *astring = #""
There is no semantic difference between NSString *astring = [[NSString alloc] init]; and NSString *astring = #""; - but NSString *astring = nil; is completely different. The first two produce a reference to an immutable string value, the last indicates the absence of a value.
Whether the various ways of generating an zero-length string produce different objects is entirely an implementation detail. The code:
NSString *a = [[NSString alloc] init];
NSString *b = [NSString new];
NSString *c = #"";
NSString *d = [NSString stringWithString:#""];
NSLog(#"%p, %p, %p, %p, %p", a, b, c, d, #""); // %p = print the value of the reference itself
outputs (the exact values will vary):
0x7fff7100c190, 0x7fff7100c190, 0x1000028d0, 0x1000028d0, 0x1000028d0
showing only 2 zero-length string objects were created - one for #"" and one for alloc/init. As the strings are immutable such sharing is safe, but in general you should not rely on it and try to compare strings using reference comparison (==).
NSString *atring = nil
is different -- it's a nil pointer, not an empty string.
NSString *astring = #""
is almost the same, if you change it to something like
NSString* astring=[#"" retain];
It's one of the things that "don't matter"; he or she simply used one way. Probably for no particular reason at all.
NSString *atring = nil; is simply setting the pointer to nil and does nothing other than ensure that pointer is set to nil;
NSString *astring = #""; is a shorthand literal and is the equivalent of [NSString stringWithString:#""];
On another point I don't know why you would want to initialize a string to nothing if its not mutable since you won't be able to change it later without overriding it.

Memory management, should I be retaining?

If I declare an NSString in my header file as follows:
{
NSString *testString;
}
#property(nonatomic,retain) NSString *testString;
Then synthesize the string in my .m file, what is the correct way to initialise it?
If I don't write:
self.testString = [[NSString alloc] init];
then the it is never initialised, but if I do, then isn't the string being retained twice? Or should I initialise it some other way, such as:
self.testString = [NSString stringWithFormat:#"%#, sampleText];
You are correct, the former will over retain the object.
Use the second form instead.
If you had to use the ivar directly however, you need to retain the object :
testString = [[NSString stringWithFormat:#"%#, sampleText] retain];
self.testString = [NSString stringWithFormat:#"%#, sampleText]; or self.testString = [NSString string]; is correct; self.testString = [[NSString alloc] init]; will cause over-retaining.
Consider using ARC (Automatic Retain Counting) for you project. With ARC the compiler takes care of retain counts so you don't have to, in fact aren't allowed to. There is a refactoring that will convert a current project.
It seems that you declare an variable called testString in your .h and you also create a property that retains.
You can either use this:
self.testString = [NSString string];
or you can use
testString = [[NSString alloc] init];
Defining the variable through the property will cause it to be retained, that's why you declared it as (nonatomic, retain). Defining the variable through the declaration won't take those arguments into consideration. Here's a quick rule of thumb about retaining.
Using your code as a base:
self.testString = [[NSString alloc] init]; // Retain count = 2
self.testString = [NSString string]; // Retain count = 1
testString = [[NSString alloc] init]; // Retain count = 1
testString = [NSString string]; // Not retained at all.
First of all #property (nonatomic, copy) NSString *testString to avoid mutability bugs.
Second - if you want just a string without leaks:
self.testString = [NSString string];
self.testString = [[[NSString alloc] init] autorelease];
self.testString = [NSString stringWithFormat:#"%#", text];
these are all valid options.

connecting three NSStrings

Right i have three NSStrings that i want to put together to make one long nsstring (to use as a URL). I have used stringByAppedingString which lets me put two of the together but i do not know how to put three together. Basically what i want to end up with is http://graph.facebook.com/517418970/picture?type=large but i need them in three separate components so i can change the number in the URl
#implementation FacebookPicturesViewController
- (IBAction) nextImagePush {
NSString *prefix = #"http://graph.facebook.com/";
NSString *profileId = #"517418970";
NSString *suffix = #"/picture?type=large";
NSString *url = [prefix stringByAppendingString:suffix];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
[imageView setImage:img];
imageCount++;
if (imageCount >= [imageArray count]){
imageCount = 0;
}
}
- (void) viewDidLoad {
imageArray = [[NSArray alloc] initWithObjects:#"image1", #"image2", nil];
imageCount = 0;
}
You could just do it in two steps:
NSString* partialUrl= [prefix stringByAppendingString:profileID];
NSString* fullUrl= [partialUrl stringByAppendingString:suffix];
Alternatively, you could use a format:
NSString* url= [NSString stringWithFormat:#"%#%#%#", prefix, profileID, suffix];
As a general solution for when you don't know ahead of time just how many strings you have to combine, you can stick them in an NSArray and use the array to join them together. So in this case:
NSArray *elementsInURL = [NSArray arrayWithObjects:prefix, profileID, suffix, nil];
NSString *combined = [elementsInURL componentsJoinedByString:#""];
You want + (id)stringWithFormat:(NSString *)format, …
Full docs are here
I'd handle the concatenation like this:
NSString *prefix = #"http://graph.facebook.com/";
NSString *profileId = #"517418970";
NSString *suffix = #"/picture?type=large";
NSString *URL = [[prefix stringByAppendingString:profileId]
stringByAppendingString:suffix];

Append string with variable

I'm a java guy coming over to Objective-C. In java, to add a variable to a string you'd have to do something along the lines of:
someString = "This string is equal to " + someNumber + ".";
I can't figure out how to do it in Objective-C though. I have an NSMutableString that I'd like to add to the middle of a string. How do I go about doing this?
I've tried:
NSString *someText = #"Lorem ipsum " + someMutableString;
NSString *someText = #"Lorem ipsum " + [someMutableString stringForm];
and a few other things, none of which seem to work. Also interchanged the +s with ,s.
You can use appendString:, but in general, I prefer:
NSString *someText = [NSString stringWithFormat: #"Lorem ipsum %#", someMutableString];
NSString *someString = [NSString stringWithFormat: #"This is string is equal to %d.", someInt];
NSString *someOtherString = [NSString stringWithFormat: #"This is string is equal to %#.", someNSNumber];
or, alternatively:
NSString *someOtherString = [NSString stringWithFormat: #"This is string is equal to %d.", [someNSNumber intValue]];
etc...
These strings are autoreleased, so take care not to lose their value. If necessary, retain or copy them and release them yourself later.
Try this:
NSMutableString * string1 = [[NSMutableString alloc] initWithString:#"this is my string"];
[string1 appendString:#" with more strings attached"];
//release when done
[string1 release];
You need to use stringByAppendingString
NSString* string = [[NSString alloc] initWithString:#"some string"];
string = [string stringByAppendingString:#" Sweet!"];
Don't forget to [string release]; when your done of course.
NSMutableString *string = [[NSMutableString alloc] init];
[string appendFormat:#"more text %#", object ];