Search This Blog

Monday, 4 March 2013

FOUNDATION KIT FRAMEWORK


NSString Datailed Discription
Strings are collections of characters that are grouped together to form words or sentences. If it wasn't for humans, computers would probably never have anything to do with strings. The fact is, however, that one of the primary jobs of a computer is to accept data from and present data to humans. For this reason it is highly likely that any Objective-C program is going to involve a considerable amount of code specifically designed to work with data in the form of strings. The purpose of this chapter is to cover the key aspects of string creation, comparison and manipulation in Objective-C using the Foundation Framework's NSString class.

Contents
[hide]
• 1 Strings without NSString
• 2 Declaring Constant String Objects
• 3 Creating Mutable and Immutable String Objects
• 4 Getting the Length of a String
• 5 Copying a String
• 6 Searching for a Substring
• 7 Replacing Parts of a String
• 8 String Search and Replace
• 9 Deleting Sections of a String
• 10 Extracting a Subsection of a String
• 11 Inserting Text into a String
• 12 Appending Text to the End of a String
• 13 Comparing Strings
• 14 Checking for String Prefixes and Suffixes
• 15 Converting to Upper or Lower Case
• 16 Converting Strings to Numbers
• 17 Converting a String Object to ASCII


1) [edit] Strings without NSString

As we've already discussed, Objective-C is built upon the C programming language. C also has a mechanism for dealing with strings, but because C is not an object oriented programming language it does not have any of the advantages offered to us through the NSString class. For example, to use the C approach to creating strings we have to set up a pointer to a string of characters:

char *myString = "This is a C character string";

Alternatively, we could define a C style character array to contain a string:
Having created the string we literally have nothing but a section of memory where a null terminated string of characters is located. If we want to do anything to manipulate the string we will have to write our own code to do it.
By using NSString, however, we get access to a wide range of methods provided with that class to manipulate our string without having to write all the code ourselves. My first ever job involved writing complex programs in the C programming language, and from bitter experience I can tell you that the hardest part of that job was writing code to work with strings. My life would have been much easier if Objective-C and the NSString class had existed all those years ago.In addition, C style character strings are composed of single byte characters and therefore limited in the range of characters that can be stored. This usually becomes a problem when dealing with non-ASCII character sets used by foreign languages. NSString objects, on the other hand, are comprised of multibyte Unicode characters and can handle just about any language character set.

[edit] Declaring Constant String Objects
A constant string object is declared by encapsulating the string in double quotes (") preceded by an @ sign. For example:
@"This is a constant character string object";
In order to display the current value of a string object using NSLog, simply reference the string using '%@' as follows:
NSLog (@"%@", @"This is a constant character string object");

Even though all we are doing here is creating a constant string object, keep in mind that this is still an object. As such, it has a range of methods that we can call on it. For example string objects have a length method that returns the number of characters in the string. We can, therefore, call this on a constant string object:
int len = [@"Hello" length];

NSLog (@"Length of string = %i", len);
The above code declares a constant string object containing the word "Hello" and calls the length method of object. The result is assigned to an integer variable named len which in turn is displayed using NSLog. When compiled and executed, we get the following output:
Length of string = 5

Constant string objects are actually instantiated from the NSConstantString class which, much like the other classes we will look at in this chapter, is actually a subclass of the NSString class. In practice, given the way that constant strings are used, it is unlikely that you will need to specifically declare your string constants as being of type NSConstantString. It is more likely that you will declare the string as we have done in this section and let the compiler handle the rest.


[edit] Creating Mutable and Immutable String Objects
Two additional types of Objective-C string objects are mutable and immutable. When you create a string object of type NSString you are creating an immutable string object. This means that once a string has been assigned to the object, that string cannot subsequently be modified in any way.
NSString *string1 = @"This string is immutable";
Mutable string objects, on the other hand, are declared using the NSMutableString class and allow the string contained within the object to be modified using a variety of methods (some of which will be covered in the remainder of this chapter). NSMutableString is a subclass of NSString, which in turn is a subclass of NSObject. Mutable strings cannot be initialized simply by assigning a constant string object as we did above since that will just give us a pointer to an immutable constant string object. Instead, the string constant must be copied into the mutable string object. For example:
NSMutableString *string2 = [NSMutableString stringWithString:@"This string is mutable"];
Once a string has been declared as immutable, the only way to get a mutable version of the string is to create a mutable string object and copy the contents of the immutable string object to it. This can be achieved using the NSMutableString stringWithString class method. For example:
NSString *string1 = @"This is a string";
NSMutableString *string2;

string2 = [NSMutableString stringWithString: string1];
Once executed, the above code will create an immutable string object (string1) initialized with the text "This is a string" and an empty pointer to an immutable string object (string2). The stringWithString class method of the NSMutableString class is then called, passing though the immutable string1 as an argument. This method returns a new object containing the immutable string and assigns it to string2. We now have a mutable copy of the immutable string1 object.

[edit] Getting the Length of a String
The length of the string in a string object can be obtained by accessing the length method of the string object:
NSString *string1 = @"This string is Immutable";

int len = [string1 length];

NSLog (@"String length is %i", len);
The above code fragment will produce the following output when executed:
String length is 24


[edit] Copying a String
When copying one string object to another it might be tempting to think that you can simply assign the object from one variable to another. For example, if we had two integer variables and wanted to assign the value of one to the other we could simply do the following:
int a = 10;
int b;

a = b;
After the above code has executed, both variables a and b will contain the value 10. The same is not, however, true of string objects. Take for example the following code fragment:
NSMutableString *string1;
NSMutableString *string2;

string1 = [NSMutableString stringWithString: @"This is a string"];

string2 = string1;
What we have achieved here is to create two variables (string1 and string2) that point to the memory location of the same string object. This is because the '*' before the variable names in the declarations indicates that this is a pointer to an object, not an actual object. Any time that we access the object referenced by either of these pointers we will, in fact, be accessing the same object. To prove this, we can make a change using the string2 reference and then display the string associated with both the string1 and string1 object pointers:
NSMutableString *string1;
NSMutableString *string2;

string1 = [NSMutableString stringWithString: @"This is a string"];

string2 = string1;

[string2 appendString: @" and it is mine!"];

NSLog (@"string1 = %@", string1);

NSLog (@"string2 = %@", string2);
The above code will display the following output, proving that both string1 and string2 point to the same object since only one reference was modified, yet both show the change:
2009-11-03 14:35:37.731 t[32239:10b] string1 = This is a string and it is mine!
2009-11-03 14:35:37.732 t[32239:10b] string2 = This is a string and it is mine!
To actually copy one string object to another string object we must use stringWithString method the NSMutableString class:

NSMutableString *string1;
NSMutableString *string2;

string1 = [NSMutableString stringWithString: @"This is a string"]; // Initialize string1

string2 = [NSMutableString stringWithString: string1]; // Copy string1 object to string2

[string2 appendString: @" and it is mine!"]; // Modify string2

NSLog (@"string1 = %@", string1);

NSLog (@"string2 = %@", string2);
When executed, the appended text appears only in the object referenced by string2 since string2 now references a different object to that referenced by string1:
2009-11-03 14:42:10.426 t[32263:10b] string1 = This is a string
2009-11-03 14:42:10.427 t[32263:10b] string2 = This is a string and it is mine!



[edit] Searching for a Substring
A common requirement when working with strings is to identify whether a particular sequence of characters appears within a string. This can be achieved using the rangeOfString method. This method returns a structure of type NSRange. The NSRange structure contains a location value providing the index into the string of the matched substring and a length value indicating the length of the match.
NSString *string1 = @"The quick brown fox jumped";

NSRange match;

match = [string1 rangeOfString: @"brown fox"];

NSLog (@"match found at index %i", match.location);

NSLog (@"match length = %i", match.length);
The NSLog call will display the location and length of the match. Note that the location is an index into the string where the match started and that the index considers the first position in a string to be 0 and not 1. As such, the location in our example will be 10 and the length will be 9.
In the event that no match is found, the rangeOfString method will set the location member of the NSRange structure to NSNotFound. For example:
NSString *string1 = @"The quick brown fox jumped";

NSRange match;

match = [string1 rangeOfString: @"brown dog"];

if (match.location == NSNotFound)
NSLog (@"Match not found");
else
NSLog (@"match found at index %i", match.location);



[edit] Replacing Parts of a String
Sections of a mutable string may be replaced by other character sequences using the replaceCharactersInRange method. This method directly modifies the string object on which the method is called so only works on mutable string objects.
This method requires two arguments. The first argument is an NSRange structure consisting of the location of the first character and the total number of characters to be replaced. The second argument is the replacement string. An NSRange structure can be created by calling NSMakeRange and passing though the location and length values as arguments. For example, to replace the word "fox" with "squirrel" in our sample mutable string object we would write the following Objective-C code:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];

[string1 replaceCharactersInRange: NSMakeRange(16, 3) withString: @"squirrel"];

NSLog (@"string1 = %@", string1);
As you may have noted from the above example, the replacement string does not have to be the same length as the range being replaced. The string object and replacement method will resize the string automatically.


[edit] String Search and Replace
Previously we have covered how to perform a search in a string and how to replace a subsection of a string using the rangeOfString and replaceCharactersInRange methods respectively. The fact that both of these methods use the NSRange structure enables us to combine the two methods to perform a search and replace. In the following example, we use rangeOfString to provide us with an NSRange structure for the substring to be replace and then pass this through to replaceCharactersInRange to perform the replacement:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];

[string1 replaceCharactersInRange: [string1 rangeOfString: @"brown fox"] withString: @"black dog"];
When executed, string1 will contain the string "The quick black dog jumped".

[edit] Deleting Sections of a String
Similar techniques to those described above can be used to delete a subsection of a string using the deleteCharactersInRange method. As with the preceding examples, this method accepts an NSRange structure as an argument and can be combined with the rangeOfString method to perform a search and delete:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];

[string1 deleteCharactersInRange: [string1 rangeOfString: @"jumped"]];


[edit] Extracting a Subsection of a String
A subsection of a string can be extracted using the substringWithRange method. The range is specified using an NSRange structure and the extracted substring is returned in the form of an NSString object:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;

string2 = [string1 substringWithRange: NSMakeRange (4, 5)];

NSLog (@"string2 = %@", string2);
When executed, the above code will output the substring assigned to string2 ("quick").
Alternatively, a substring may be extracted from a given index until the end of the string using the subStringFromIndex method. For example:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;

string2 = [string1 substringFromIndex: 4];
Similarly, the subStringToIndex may be used to extract a substring from the beginning of the source string up until a specified character index into the string.


[edit] Inserting Text into a String
The insertString method inserts a substring into a string object and takes as arguments the NSString object from which the new string is to inserted and the index location into the target string where the insertion is to be performed:
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];

[string1 insertString: @"agile, " atIndex: 4];


[edit] Appending Text to the End of a String
Text can be appended to the end of an existing string object using the appendString method. This method directly modifies the string object on which the method is called and as such is only available for mutable string objects.
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];

[string1 appendString: @" over the lazy dog"];

NSLog (@"string1 = %@", string1);


[edit] Comparing Strings
String objects cannot be compared using the equality (==) operator. The reason for this is that any attempt to perform a comparison this way will simply compare whether the two string objects are located at the same memory location. Let's take a look at this via an example:
NSString *string1 = @"My String";
NSString *string2 = @"My String";

if (string1 == string2)
NSLog (@"Strings match");
else
NSLog (@"Strings do not match");
In the above code excerpt, string1 and string2 are pointers to two different string objects both of which contain the same character strings. If we compare them using the equality operator, however, we will get a "Strings do not match" result. This is because the if (string1 == string2) test is asking whether the pointers point to the same memory location. Since string1 and string2 point to entirely different objects the answer, obviously, is no.
We can now take this a step further and change the code so that both string1 and string2 point to the same string object:
NSString *string1 = @"My String";
NSString *string2;

string2 = string1;

if (string1 == string2)
NSLog (@"Strings match");
else
NSLog (@"Strings do not match");
Now when we run the code, we get a "Strings match" result because both variables are pointing to the same object in memory.
To truly compare the actual strings contained within two string objects we must use the isEqualToString method:
NSString *string1 = @"My String";
NSString *string2 = @"My String 2";

if ([string1 isEqualToString: string2])
NSLog (@"Strings match");
else
NSLog (@"Strings do not match");
Another option is to use the compare method (to perform a case sensitive comparison) or the caseInsenstiveCompare NSString methods. These are more advanced comparison methods that can be useful when sorting strings into order.


[edit] Checking for String Prefixes and Suffixes
A string object can be tested to identify whether the string begins or ends with a particular sequence of characters (otherwise known as prefixes and suffixes). This is achieved using the hasPrefix and hasSuffix methods respectively, both of which return boolean values based on whether a match is found or not.
NSString *string1 = @"The quick brown fox jumped";

BOOL result;

result = [string1 hasPrefix: @"The"];

if (result)
NSLog (@"String begins with The");

result = [string1 hasSuffix: @"dog"];

if (result)
NSLog (@"String ends with dog");


[edit] Converting to Upper or Lower Case
The Foundation NSString classes provide a variety of methods for modifying different aspects of case within a string. Note that each of these methods returns a new string object reflecting the change, leaving the original string object unchanged.
• capitalizedString
Returns a copy of the specified string with the first letter of each word capitalized and all other characters in lower case:
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;

string2 = [string1 capitalizedString];

The above code will return a string object containing the string "The Quick Brown Fox Jumped" and assign it to the string2 variable. The string object referenced by string1 remains unmodified.
• lowercaseString
Returns a copy of the specified string with all characters in lower case:
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;

string2 = [string1 lowercaseString];
The above code will return a string object containing the string "the quick brown fox jumped" and assign it to the string2 variable. The string object referenced by string1 remains unmodified.
• uppercaseString
Returns a copy of the specified string with all characters in upper case:
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;

string2 = [string1 uppercaseString];
The above code will return a string object containing the string "THE QUICK BROWN FOX JUMPED" and assign it to the string2 variable. The string object referenced by string1 remains unmodified.


[edit] Converting Strings to Numbers
String objects can be converted to a variety of number types:
• Convert String to int
NSString *string1 = @"10";

int myInt = [string1 intValue];

NSLog (@"%i", myInt);
• Convert String to double
NSString *string1 = @"10.1092";

double myDouble = [string1 doubleValue];

NSLog (@"%f", myDouble);
• Convert String to float
NSString *string1 = @"10.1092";

float myFloat = [string1 floatValue];

NSLog (@"%f", myFloat);
• Convert String to NSInteger
NSString *string1 = @"10";

NSInteger myInteger = [string1 integerValue];

NSLog (@"%li", myInteger);

[edit] Converting a String Object to ASCII
The string contained within a string object can be extracted and converted to an ASCII C style character string using the UTF8String method. For example:
NSString *string1 = @"The quick browen fox";

const char *utfString = [string1 UTF8String];

printf ("Converted string = %s\n", utfString);

------------------------------------------------------------------------------------------

//NSArray

//How to create an array and initialize it
NSArray *array = [[NSArray alloc]init];
(or)
NSArray*array=[[NSArray alloc]initWithObjects:@"one",@"two",@"three",nil]; //Here Array is initialized with three String Elements
(or)
NSArray *array2 = [[NSArray alloc]initWithArray:array]; //Here array2 is initialized with the same three elements
(or)
NSArray *array = [[NSArray alloc]initWithContentsOfFile:path]; //Give the path and it will get the Elements

//w/o alloc and init methods
NSArray *array = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];
NSArray *array = [NSArray arrayWithArray:array2];


//If u need only single element in a array
NSArray *array = [NSArray arrayWithObject:@"one"];

//How to get the Count of an Array
int length = [array count];

//How to Add an Element to the array
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"one",nil];
[array insertObject:@"two" atIndex:1];
[array insertObject:@"three" atIndex:2];

//How to Delete an Element From the Array
[array removeObjectAtIndex:1];

//How to remove Lase Object
[array removeLastObject];


//How to search an element in the Array
if([array containsObject:@"two"])
{
//do this
}

//Displaying the Array Description
NSLog(@"The Array is %@",[array descriptionWithLocale:nil]);
NSLog(@"The Array is %@",[array description]);

//How to get the array element Index
[array indexOfObject:@"two"];

------------------------------------------------------------------------------------------------------------

NSDictionary


Objective-C Dictionary Object classes allow data to be stored and managed in the form of key-value pairs where both the key and the value are objects.
Contents

• 1 What are Dictionary Objects?
• 2 Creating Dictionary Objects
• 3 Initializing and Adding Entries to a Dictionary Object
• 4 Getting an Entry Count
• 5 Accessing Dictionary Entries
• 6 Removing Entries from a Dictionary Object


What are Dictionary Objects?
In the previous chapter we looked at using array objects to store collections of objects. Dictionary objects fulfill a similar purpose except each object stored in the dictionary has associated with it a unique key (to be precise, the key is unique to the particular dictionary object). The unique key can be of any object type though to be useful they are typically string objects.
Objective-C dictionary objects are created using the NSDictionary and NSMutableDictionary classes. NSDictionary based objects are immutable (in other words once they have been created and initialized their contents cannot be modified). Mutable dictionaries are instantiated from the NSMutableDictionary class and may be modified after creation and initialization.
Creating Dictionary Objects
An empty, immutable dictionary object may be created as follows:
NSDictionary *bookListing = [NSDictionary dictionary];
Similarly, an empty mutable dictionary may be created as follows:
NSMutableDictionary *bookListing = [NSMutableDictionary dictionary];

Initializing and Adding Entries to a Dictionary Object
Each key-value pair contained within a dictionary is referred to as an entry. Once a relationship between a key and a value has been estabilshed that relationship cannot subsequently be modified.
New entries are added to a dictionary using the setObjectinstance method. This method takes as its arguments an object and a corresponding key:
NSMutableDictionary *bookListing = [NSMutableDictionary dictionary];

[bookListing setObject: @"Wind in the Willows" forKey: @"100-432112"];
[bookListing setObject: @"Tale of Two Cities " forKey: @"200-532874"];
[bookListing setObject: @"Sense and Sensibility" forKey: @"202-546549"];
[bookListing setObject: @"Shutter Island" forKey: @"104-109834"];
In the above example, the bookListing dictionary is initialized with four book names with corresponding reference codes to act as keys.
It is also possible to create and initialize a dictionary with a number of key-value pairs using thedictionaryWithObjectsAndKeys class method. For example, an alternative to the above code is as follows:
NSDictionary *bookListing = [NSDictionary dictionaryWithObjectsAndKeys: @"Wind in the Willows", @"100-432112", @"Tale of Two Cities ", @"200-532874", @"Sense and Sensibility", @"202-546549", @"Shutter Island", @"104-109834", nil];
Dictionaries may also be initialized using keys and values contained in arrays using the arrayWithObjects method:
NSArray *objectsArray = [NSArray arrayWithObjects: @"Wind in the Willows", @"Tale of Two Cities ", @"Sense and Sensibility", @"Shutter Island", nil];
NSArray *keysArray = [NSArray arrayWithObjects: @"100-432112", @"200-532874", @"202-546549", @"104-109834", nil];

NSDictionary *bookListing = [[NSDictionary alloc] initWithObjects: objectsArray forKeys: keysArray];

Getting an Entry Count
A count of the number of entries in a dictionary can be obtained using the count instance methods:
NSMutableDictionary *bookListing = [NSMutableDictionary dictionary];

int count;

[bookListing setObject: @"Wind in the Willows" forKey: @"100-432112"];
[bookListing setObject: @"Tale of Two Cities " forKey: @"200-532874"];
[bookListing setObject: @"Sense and Sensibility" forKey: @"202-546549"];
[bookListing setObject: @"Shutter Island" forKey: @"104-109834"];

NSLog (@"Number of books in dictionary = %i", [bookListing count]);

Accessing Dictionary Entries
Dictionary entries are accessed by referencing the key corresponding to the required entry via the objectForKeymethod. For example:
NSLog ( @"100-432112 = %@", [bookListing objectForKey: @"100-432112"]);
NSLog ( @"200-532874 = %@", [bookListing objectForKey: @"200-532874"]);
NSLog ( @"202-546549 = %@", [bookListing objectForKey: @"202-546549"]);
NSLog ( @"104-109834 = %@", [bookListing objectForKey: @"104-109834"]);
When combined with the previous code and executed, we would expect to see the following output:
100-432112 = Wind in the Willows
200-532874 = Tale of Two Cities
202-546549 = Sense and Sensibility
104-109834 = Shutter Island

Removing Entries from a Dictionary Object
Specific dictionary entries may be removed by referencing the key as an argument to theremoveObjectForKey method. For example, to remove the book entry for "Shutter Island" we would write the following code:
[bookListing removeObjectForKey: @"104-109834"];
All entries in a dictionary may be removed using theremoveAllObjects instance method:
[bookListing removeAllObjects];

------------------------------------------------------------------------------------------------------------

Casting


A few days ago Christopher & I chatted with an iPhone in Action reader about why Listing 18.3 in the book generated the warning "Warning: 'UIView' may not respond to -addPic:at:'". The answer is casting, and I think it's a topic that deserves some additional discussion.

All About Casting

Casting is a fundamental of C. Wikipedia defines it as an "explicit type conversion." We demonstrate it briefly on p.156, where we show that you can turn a float into an int with a little bit of casting magic:
float a = 6.00;
int b;
b = (int) a;
Beyond that, we give it pretty short attention. That's probably great for folks with experience with rigorous programming languages, but less useful for those of you just getting into them for the first time.
So in this article I'm going to talk more about casting by concentrating on three three times that I've seen it most in SDK development (and thus where you're most likely to encounter it). In order I'm going to cover: toll-free bridging; math casts; and, finally, method casts (the topic that got us started).

Toll-Free Bridging

This is the other cast-related topic that we covered pretty extensively in iPhone in Action. There are some details on p.157 (at the end of the discussion of casting) and on p.321 (in the "Using Core Fondation" box).
Much of your iPhone programming will be done using Cocoa frameworks, such as the UI and NS libraries. However, sometimes you'll have to instead use Apple's older libraries, such as Core Foundation. Core Foundation is object-oriented, just like the NS libraries, and as a result you end up with alternative ways to represent a lot of standard variable types. For example Core Foundation's CFStringRef and Cocoa's NSString * are alternate ways to represent strings.
Fortunately, Apple recognizes this equivalence and "toll-free bridges" equivalent Core Foundation and NS classes. In order to use one in the place of another, you just need to cast it, as we do throughout Listing 16.11 (pp.318-320):
(NSString *)ABRecordCopyCompositeName(thisPerson);
This sort of casting will come up frequently if you use older frameworks, such as Address Book and Core Graphics.

Math Casting

I've run into the most problem with casting when I was writing mathematical formulas. Listing 17.10 (pp.340-341) shows off one such examples. Most of the way through that example, you can see a line which reads:
int currentHeight = 395 - ceil((float)newLocation.altitude/savedDestinationHeight*(401-65));
Clearly, that's a cast, but I don't really explain why in the description of the code.
I had to cast because of the "int" variable that I'm saving the formula off to. A problem arises because there's not necessarily a consensus (among all programming languages) for how to treat the right-hand side of such an equation. Should the elements all be treated as integers, or should they be left in their native form until the final conversion is done? Apple's Objective-C appears to assume a conversion to the final variable type almost immediately.
In this situation that resulted in altitude/height being made into an integer before it was multiplied by 401-65, which was not the desired result, because I was trying to generate a percent (meaning that 0 or 1 was really not useful). Thus the cast of that division as a float.
I find this sort of thing to be the one situation where a cast is really required ... where leaving it out results in your program not working, and it can be very confusing to figure out why.

Method Casting

And so finally we come to query that started this article off. If you compile the code associated with Listing 18.3, you'll see "Warning: 'UIView' may not respond to -addPic:at:'". This is a non-fatal warning that has to do with yet another casting nuisance. You'll find the line that generates the warning at the top of p.353:
[self.view addPic:myImageView.image at:myImageView.frame];
If you think about it, the reason for this warning should jump out. The view controller's view property is defined as a UIView, which does not contain the addPic:at: method introduced in CollageView. Thus, if you don't like the warning, you can just cast the property appropriately:
[(collageView *)self.view addPic:myImageView.image at:myImageView.frame];
You can run into this sort of thing when a property or method assumes a very specific class of object, rather than the more general "id." If memory serves I also hit it when using the nextResponder method (probably in Listing 14.2 on p.247).

Some Final Words on Casting Warnings

It's important to note that casting problems will generally result in warnings.You don't have to resolve them. In particular a warning about uncasted toll-free bridging or a warning about an uncasted method isn't a problem as long as you know what you're doing. It's usually worth fixing them, just to make sure that you understand the reason for the warning, but you don't have to if you're doing something quick-and-dirty or have some reason to leave the warning in.
(In the case of the warning generated by Listing 18.3 we opted to leave out the casting to keep the code more readable, not really thinking about the fact that people might be concerned about the warning if they compiled the code.)
Much more insidious are the math-related casting problems which probably won't generate a warning at all. In my opinion, they're what you really have to watch out for--and they're also a good reason to generally be conscientious about casting all the time, so that you don't run into mystery problems without warnings when you get careless about math casts.

------------------------------------------------------------------------------------------------------------

NSTimer

Timers

This timer will call myMethod every 1 second.

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
What if you need to pass an object to myMethod? Use the "userInfo" property.
1. First create the Timer
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myMethod) userInfo:myObject repeats:YES];
2. Then pass the NSTimer object to your method:
-(void)myMethod:(NSTimer*)timer
{
// Now I can access all the properties and methods of myObject [[timer userInfo]myObjectMethod];
}
To stop a timer, use "invalidate":
[myTimer invalidate];
myTimer = nil; // ensures we never invalidate an already invalid Timer

------------------------------------------------------------------------------------------------------------

NSThread

1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:

- (void)myMethod { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
}
What if you need to do something to the main thread from inside your new thread (for example, show a loading symbol)? Use performSelectorOnMainThread.

[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

------------------------------------------------------------------------------------------------------------


NSUserDefaults


Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];


NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
@"", kDefaultsUsernameKey,
@"", kDefaultsPasswordKey,
nil];

[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
[[NSUserDefaults standardUserDefaults] synchronize];

------------------------------------------------------------------------------------------------------------

NSSet and NSMutableSet
//NSSet
NSSet *aSet = [NSSet alloc]initWithObjects
NSSet *aSet = [NSSet setWithObjects:@"one",@"two",@"three",nil];
[aSet initWithObjects:@"",@"",nil];
[aSet initWithSet:set2];
[aSet initWithArray:array];

//Count of an Set
[aSet count];

//Operations in Set
1.Intersection
[aSet intersectsSet:set2];
2.Union
[aSet unionSet:set2];
3.Remove Objects
[aSet removeObjects];
4.Minus
[aSet minusSet:set2];


//Adding Objects to the Set
NSMutableSet *mSet = [NSMutableSet setWithObjects:@"",nil];

[mSet setByAddingObject:@"Kumar"];
[mSet setByAddingObjectsFromSet:set2];
[mSet setByAddingObjectsFromArray:array];

------------------------------------------------------------------------------------------------------------

NSDate


NSDate *currentDate = [NSDate date];
//To print Current date
NSLog(@"the date is %@",currentDate); //it displays with time

//How to add time to Date
[NSDate dateWithTimeIntervalSinceNow:60*60]; //It will add 1 hour to the present time

//How to manually give the Dates
[NSDate dateWithStrin]

//How to compare Dates
if([currentDate isEqualToDate:date2])

//print Description
[currentDate description];


------------------------------------------------------------------------------------------------------------
NSNumber and NSDecimal Number
//NSNumber and NSDecimalNumber
NSNumber *aNumber = [NSNumber numberWithInt:21];
NSNumber *aNumber = [NSNumber numberWithChar:'c'];
NSNumber *aNumber = [NSNumber numberWithBool:YES:];
NSNumber *aNumber = [NSNumber numberWithFloat:3.2:];

//How to print an number
NSLog(@"the number is %@",aNumber); //Done use %d because aNumber is an type Object

//How to convert aNumber to an Integer value
int x = [aNumber intValue];
float x = [aNumber floatValue];
BOOL x = [aNumber boolValue];

//How to add NSNumber value to the Array
NSArray *arr = [NSArray arrayWithObject:aNumber];

NSArray *arr = [NSArray arrayWithObject:x]; //wrong bcz x is an primitive data type


//NSDecimalNumber
//Mainly this class used for storing the decimal values
NSDecimalNumber *dNumber = [[NSDecimalNumber alloc]initWithString:@"23.3"];







No comments:

Post a Comment