NSString *myString = @"This is my string";
You can use an NSString object in the alert that you learned about last week. Here is how you would use the NSString object "myString" in an alert:
NSString *myString = @"This is my string";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UIAlertView"
message:myString
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UIAlertView"
message:myString
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
Notice that the "message" argument of the alert you created above uses the NSString object as an argument. Another thing you will be doing with strings is combining strings to make new ones.
For instance, if I had two strings - a first and a last name - and I wanted to create a new string for a full name I could do something like this:
NSString *firstName = @"Matt";
NSString *lastName = @"Campbell";
NSString *fullName = [NSString stringWithFormat:@"My name is %@ %@",
firstName, lastName];
If you were to put fullName into an alert it would say "My name is Matt Campbell". How the stringWithFormat function works is that you give it a string with special symbols in it. The function will replace the symbols with the strings in give it as the next arguments to the function.
If you were to put fullName into an alert it would say "My name is Matt Campbell". How the stringWithFormat function works is that you give it a string with special symbols in it. The function will replace the symbols with the strings in give it as the next arguments to the function.
Note that when you are using the alert object you need to follow the "alloc, use, release" pattern while the NSString only requires you to use the function after which you may safely forget about it.
This has something to do with the memory management features of the iPhone. Essentially, when you use an object's "alloc" you need to "release" at some point in the future. NSString does not use an alloc in this instance so it does not need to be released while UIAlert does. More details about memory management will be discussed in this mailing list in the future.
No comments:
Post a Comment