ArticleDirectory
- Nsstringnsmutablestring
- Date times
- Nsarraynsmutablearraydictionary
- Nsnotification
- Event Response
- MVC
- Delegate
- Target-action
- Categories
- Singletons
Common class nsstringnsmutablestring in cocoa
Assignment |
Nsstring * mystring = @ "some string "; Nsstring * mystring = [nsstringstringwithformat: @ "Object =%@", someobject]; |
Conversion |
Nsstring * upper = [mystringuppercasestring]; Intintstring = [mystringintvalue]; |
Content Removal |
Nsstring * trimmed = [mystring string bytrimmingcharactersinset: [nscharacterset whitespace characterset]; |
Truncate string |
Nsstring * astring = [numberstringsubstringtoindex: 3]; Nsange range = nsmakerange (4, 3 ); Nsstring * astring = [numberstringsubstringwithrange: range]; Nsarray * arr = [numberstring Componentsseparatedbystring: @ ""]; |
Replace |
Nsstring * astring = [numberstringstringbyreplacingoccurrencesof String: @ "three" withstring: @ "four"]; |
Search |
Nsangefoundrange = [numberstringrangeofstring: @ "two"]; Bool found = ([numberstringrangeofstring: @ "two"]. location! = Nsnotfound ); |
File |
Nsstring * filecontents = [nsstringstringwithcontentsoffile: @ "myfile.txt"]; Nsurl * url = [nsurl urlwithstring: @ "http://google.com"]; Nsstring * pagecontents = [nsstringstringwithcontentsofurl: url]; |
Date times
Nsdate * mydate = [nsdate date];
Nstimeintervalsecondsperday = 24*60*60;
Nsdate * Now = [nsdate date];
Nsdate * Yesterday = [now addtimeinterval:-secondsperday];
Nsdatecomponents * comp = [[nsdateco M ponentsalloc] init];
[Co m p setmonth: 06];
[Co m p setday: 01];
[Co m p setyear: 2010];
Nscalendar * mycal = [[nscalendaralloc] initwithcalendaridentifier: nsgregoriancalendar];
Nsdate * mydate = [mycaldatefromcomponents: comp];
Nsarraynsmutablearraydictionary
Nsstring * string1 = @ "one ";
Nsstring * string2 = @ "two ";
Nsstring * string3 = @ "three ";
Nsarray * myarray = [nsarrayarraywithobjects: string1, string2, string3, nil];
For (nsstring * OBJ in myarray ){
Nslog (@ "% @", OBJ );
}
For (nsstring * OBJ in [myarrayreverseobjectenumerator])
{
Nslog (@ "% @", OBJ );
}
Nsarray * arr1 = [nsarrayarraywith objects: @ "iPhone", @ "iPod", nil];
Nsdictionary * mydict = [[nsdictionar y alloc] dictionarywithobjectsandkeys: arr1, @ "mobile", arr2, @ "computers", nil];
For (ID key in mydict ){
Nslog (@ "key: % @, value: % @",
Key, [mydictobjectforkey:
Key]);
}
[Mydict setobject: string2 forkey: @ "Media"];
Nsnotification
Notiications provide a handy way for youto pass information between objects in your application without needing a direct reference between them. which contains a name, an object (often the object posting the notification), and an optional dictionary.
Registration message, message processing method, logout
[[Nsnotificationcenterdefacenter] addobserver: Self selector: @ selector (dosomething :)
Name: @ "mynotification"
Object: Nil];
-(Void) deallc
{
[[Nsnotificationcenterdefacenter] removeobserver: Self];
[Superdealloc];
}
-(Void) dosomething :( nsnotification *) Anote
{
Nsdictionary * mydict = [anoteobject];
Nslog (@ "% @", mydict );
}
Send message
[[Nsnotifcencenterdefacenter] postnotificationname: my_notificationobject: mydict];
Memory Management
IOS does not support GC. Therefore, you must manually release the created object. [Note that the Creator is responsible for releasing the object, such as the object of the factory method, which does not need to be released by the caller.]
[Object release];
Remember this basic rule of thumb: Any time you call the alloc, copy, or retainmethods on an object, you must at some point later call the release method.
The autorelease alternative
If you're responsible for the creation of an object and you're going to pass it off to some other class for usage, you shoshould autorelease the object before you send it off.
This is done with the autorelease method:
[Objectautorelease];
You'll typically send the autorelease message just before you return the object at the end of a method. after an object has been autoreleased, it's watched over by a special nutoreleasepool. the object is kept alive for the scope of the method to which it's been passed, and then the NSAID utoreleasepool cleans it up.
-(Nsstring *) makeusername
{
Nsstring * name = [[nsstringalloc] initwithstring: @ "new name"];
Return [name autorelease];
}
In the preceding example, the returned object is released by the NSAID pool. The disadvantage is that the released object is not fixed at the time of release, and the system memory is occupied before release. The caller does not need to handle the release issue. However, when using the retain method, A pair of release must be called to balance the reference count.
Use uikitLibrary example
Uibutton * mybutton = [uibuttonbuttonwithtype: uibuttontyperoundedrect];
In most cases, the cocoa touch frameworks use a naming convention to help you decide when you need to release objects: if the method name starts with the word alloc, new, or copy, then you shoshould call releasewhen you are finished with the object.
Retaining and counting
What if you want to hold onto an object that has been passed to you and that will be autoreleased? In that case, you send it a retain message:
[Object retain];
When you do this, you're saying you want the object to stay around und, but now you're 've become responsible for its memory as well: you must send a release message at some point to balance your retain.
Event Response
Bare events (or actions)
Delegated events
Notification
Books iPhone and iPad in actionDetailed description of chapter6
Design Mode MVC
The Model View Controller (MVC) pattern separates an application's data structures (the model) from its user interface (the view), with a middle layer (the Controller) providingthe "glue" between the two. the controller takes input from the user (via the view), determines what action needs to be passed med, and passes this to the model for processing. the controller can also act the otherway: passing information from the model to the view to update the user interface.
Delegate
The delegate pattern is useful as an alternative to subclassing, allowing an object to define a method but assign responsibility for implementing that method to a different object (referred to as the delegate objector, more commonly, the delegate ).
Delegates need not implement all (or even any) of the delegate methods for the source object. In that case, the source object's default behavior for the method is often used.
In the following example, the behavior of the control is changed by Delegate [the keyboard is not displayed]
-(Bool) textfieldshouldbeginediting: (uitextfield *) textfield
{
Return no;
}
-(Void) viewdidload {
Cgrectrect = cgrectmake );
Uitextfiled * mytextfield = [[uitextfieldalloc] initwithframe: rect];
Mytextfield. Delegate = self;
[Self. viewaddsubview: mytextfield];
[Mytextfield release];
}
Target-action
The following example shows the Response Processing of a button.
-(Void) buttontap: (ID) sender
{
Nslog (@ "button tapped ");
}
-(Void) viewdidload {
....
[Mybutton addterget: Self action: @ selector (buttontap :) forcontrolevents: uicontroleventtouchupinside];
...
}
Categories
Like delegates, categories provide an alternative to subclassing, allowing you to add new methods to an existing class. the methods then become part of the class definition and are available to all instances (and subclasses) of that class.
In the preceding example, an extended method is added to the class uiimage so that callers can call this method, which is lighter than the inheritance method.
Singletons
Single Instance, cocoa has a lot of this mode
For example
Float level = [[uidevicecurrentdevice] batterylevel];
...
Program Life Cycle