Programming with Objective-c (Fri)

Source: Internet
Author: User



The main content of this section is OC Language Foundation, the OC is more familiar with the content of this article can not be read, basically is to translate the official documents.



The main content of this article is about the language basis of OC, mainly for values and sets. In fact, the values in OC can be divided into two categories, one is the type provided by the C language, and the other is the type that OC provides for us.



The C language provides the types that are int, float, char, and in OC, we use objects to represent a value, so the main types are Nsinteger, Nsuinteger, and CGFloat. The benefit of these types provided by the C language is that we do not need to use an object to represent the value. But when it comes to the operation of collections, what we often need is the type provided in OC.


Basic types of C language


The basic types in C are introduced first, and their use is simple:


int someInteger = 42;
    float someFloatingPointNumber = 3.1415;
    double someDoublePrecisionFloatingPointNumber = 6.02214199e23;


Of course, in OC we can also use these basic types directly, such as declaring them as properties:


@interface XYZCalculator : NSObject
@property double currentValue;
@end


When declared as a property, we can also use the dot operator to access it inside the class, because this layer of access is primarily based on access methods to get and set the value, so we use the type of C or OC type is not very different.


Basic types in Objective-c


The bool type is used in OC to hold the Boolean value, and its value is yes or NO. In the methods contained in Cocoa or Cocoa Touch, the parameters generally use Nsinteger or cgfloat of this type of value. For example, the method in Nstableviewdatasource and the Uitableviewdatasource protocol is used for the value of the Nsinteger type.



Whether Nsinteger or Nsuinteger, their range is related to the target structure, such as running on a 32-bit system, they are 32-bit values, and if they run under 64 bits, they will occupy 64 bits of space. When using the system API, Apple recommends using a value such as nsinteger as a parameter pass.


Structural body


In the Cocoa and Cocoa Touch APIs, you can sometimes use structs in C to store their values, such as:


NSString *mainString = @"This is a long string";
    NSRange substringRange = [mainString rangeOfString:@"long"];


The nsrange in this place actually gets a struct that contains the starting value of a long string in the original string, and the length of the string long.


Objects can also be used to represent values


If you need an object to represent a basic type of value, then you can use the basic type provided by Cocoa and Cocoa Touch, and we typically use objects to represent values when using collections.


The string uses the NSString object to represent


In a lot of the previous code, we'll see the NSString class, which is used to represent a string. In OC, if we want to create an object of the NSString class, we can take many methods, such as using the Standard Alloc init method, or using the factory method, or you can do it directly with literal values:


NSString *firstString = [[NSString alloc] initWithString:"Hello World!" encoding:NSUTF8StringEncoding];


The above code can be used to create a string object from an existing string. However, the string object created here is immutable, meaning that once we create the string object, we cannot modify its contents. If we need a different string, then we can only create a new string object, such as:


NSString * name = @ "John"; name = [name stringByAppendingString: @ "ny"]; // returns a new string object


One thing to note is that for a normal string object, we use stringbyappendingstring: The last thing we get is a new string object, so we need a variable to accept it and use [name] directly. Stringbyappendingstring:] In this form we are not able to accept the newly generated string object, and name still points to the original string.



So if our string is likely to change, then we need an object of the Nsmutablestring class, which is a subclass of the NSString class, or a mutable version of NSString. Based on the object of the Nsmutablestring class, we can modify the string directly, for example:


NSMutableString *name = [NSMutableString stringWithString:@"John"];    [name appendString:@"ny"];


In addition, in fact, the implementation of nsmutablestring is not difficult, as we used before we will take the name = [name stringbyappendingstring:] This form, not to say that the process does not produce a new string object, Instead of Cocoa the process, we used the code more succinctly, while Cocoa provided some new ways for us to use it.


Formatted string


Formatted strings are available in each programming language, essentially using a substitution character to insert variables into a string in a custom format. Formatting the string is still pretty big, and it's pretty flexible in terms of form. The specific code is as follows:


int magicNumber = ...NSString *magicString = [NSString stringWithFormat:@"The magic number is %i", magicNumber];
Numbers can be represented by an instance of the NSNumber class


In fact, the NSNumber class can be used to represent basic types in the C language, including char, double, float, int, long, short, and the corresponding unsigned variable, in addition to the BOOL value in OC can also be used NSNumber Representation of the. Similarly, instances of NSNumber can be instantiated in different ways:


NSNubmer *magicNumber = [[NSNumber alloc] initWithInt:42];
NSNumber *unsignedNumber = [[NSNumber alloc] initWithUnsignedInt:42u];
NSNumber *longNumber = [[NSNumber alloc] initWithLong:42l];

NSNumber *boolNumber = [[NSNumber alloc] initWithBOOL:YES];

NSNumber *simpleFloat = [NSNumber numberWithFloat:3.14f];
NSNumber *betterDouble = [NSNumber numberWithDouble:3.1415926535];

NSNumber *someChar = [NSNumber numberWithChar:‘T‘];


For the NSNumber class, we can also initialize directly using literal literals:


NSNumber *magicNumber = @42;
NSNumber *unsignedNumber = @42u;
NSNumber *longNumber = @42l;

NSNumber *boolNumber = @YES;

NSNumber *simpleFloat = @3.14f;
NSNumber *betterDouble = @3.1415926535;

NSNumber *someChar = @‘T‘;


This notation is the same as the direct instantiation of the factory method.


Use Nsvalue to represent other values


The previously mentioned NSNumber is actually a subclass of Nsvalue, and its primary function is to encapsulate a single value or a data item. Nsvalue can also be used to represent pointers or structs, compared to the basic types in the C language. Nsvalue provides a number of factory methods that allow us to create a value directly from a struct, such as Nsrange, with the following usage:


NSString *mainString = @"This is a long string";
NSRange substringRange = [mainString rangeOfString:@"long"];
NSValue *rangeValue = [NSValue valueWithRange:substringRange];


Of course, some custom structures can also be stored in Nsvalue objects, such as:


struct MyIntegerFloatStruct aStruct;
aStruct.i = 42;
aStruct.f = 3.14;

NSValue *structValue = [NSValue value:&aStruct
                         withObjCType:@encode(MyIntegerFloatStruct)];
A collection is basically an object


In the C language, the way we represent a collection is primarily an array, which stores a series of variables of the same kind. In OC, the collection is primarily an example of a collection class in Cocoa and Cocoa Touch, such as Nsarray, Nsset, and Nsdictionary. These classes, the main role is to manage a set of objects, that is, the basic type of C language is not directly into the set of OC, if you want to put in, you have to put them into the Nsnubmer or Nsvalue instances, and then add these instances to the collection.



For collections in OC, it is important to note that they are not copies of objects, but the objects themselves, and are saved in a strongly referenced form. So the objects placed in the collection want to be released, at least first set to be released. In addition, because the object itself is stored directly, it is very convenient if we need to get an object from the collection and perform certain operations. Similarly, Nsarray, Nsset, nsdictionary itself are immutable, and they all have a mutable subclass.


Array


The difference between an array and the other two collections is that it holds objects that are ordered, just like in other languages, where we access the subscript, which represents the order of the objects.


Creation of arrays


Arrays are created in the same way as some of the previously mentioned values, and can be obtained by multiple instantiations:


+ (id)arrayWithObject:(id)anObject;
+ (id)arrayWithObjects:(id)firstObject, ...;
- (id)initWithObjects:(id)firstObject, ...;


The uniqueness of the two methods of Arraywithobjects and Initwithobjects is that their last parameter is nil, so if the value of an object in the middle of the object that we insert is nil, then the last array we get will only go to this object, Because the compiler determines that nil is the end point of the initialization, this place needs to be noted.


Array of queries


For array objects, we can get some of these information, such as:


NSUInteger numberOfItems = [someArray count];

if ([someArray containsObject:someString]) {
    ...
}


The above is for the number of objects in the array and whether or not to have an object, we can also use subscript to get an object, of course, this time if the access is out of the system will still error, so generally before the visit will still make a layer of judgment:


if ([someArray count] > 0) {
    NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
}


In addition, subscript access in fact, in addition to using Objectatindex: form, we can also use the brackets to access, which is consistent with the subscript access to arrays in other languages.


Sorting of arrays


As mentioned before, one of the characteristics of an array is that it contains elements that are ordered, which means that we can adjust the order of the elements. However, when sorting arrays, it is important to note that the array itself is immutable, so a new array is generated after the sort, and we need to use an object to save the result. To make an analogy:


NSArray *unsortedStrings = @[@"gammaString", @"alphaString", @"betaString"];
NSArray *sortedStrings =
             [unsortedStrings sortedArrayUsingSelector:@selector(compare:)];


Here is a method of the NSString class compare:, of course, we can also customize a method to achieve the function of sorting, but this custom method needs to pay attention to one thing, that is, according to the principle of comparison, if the result is small then should return Nsorderedascending, the big words return to nsordereddescending, equal return nsorderedsame.


Variable group


A variable group is actually a subclass of an array, adds a mutable property, and has a series of variable-related methods.


NSMutableArray *mutableArray = [NSMutableArray array];
[mutableArray addObject:@"gamma"];
[mutableArray addObject:@"alpha"];
[mutableArray addObject:@"beta"];

[mutableArray replaceObjectAtIndex:0 withObject:@"epsilon"];


For mutable arrays, we can also use Sortusingselector: to sort.


Set


In fact, in all classes used to hold objects, the concept of the set should be more confusing. First, it is unordered, and the objects it contains are unique. What must be said, the set is simply to show that it contains these objects can be classified as a category, in addition, there is no other meaning. As for its initialization, it is basically the same as the array.



Because the collection is not much, and it is really easy to confuse people, here is not much to say, interested can directly read the Official document explanation: https://developer.apple.com/library/ios/documentation/Cocoa/ conceptual/collections/articles/sets.html#//apple_ref/doc/uid/20000136.


Dictionary


A dictionary is also a special collection because it does not have an ordered or unordered problem, and it contains content that is presented in the form of a key-value pair. Whether we want to put objects in or get objects from them, we are accessing them based on keys. For setting the key, it is best to use a string as the key. Of course, it is possible to use other objects as keys, but when the dictionary gets the key, it takes a copy, so the object we use as the key must implement the Nscopying protocol.


Create a dictionary


The creation of dictionaries can also be implemented using regular initialization and factory methods, such as:


NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
               someObject, @"anObject",
         @"Hello, World!", @"helloString",
                      @42, @"magicNumber",
                someValue, @"aValue",
                         nil];


For nsdictionary This class, it is important to note that when we initialize, it is the first to pass the object and then pass the key, which is different from other programming languages, must pay attention to when using.


Query for Dictionaries


As mentioned before, the dictionary holds the key-value pair, the access mode of the key-value pair is the key to get the value, that is, the following:


NSNumber *storedNumber = [dictionary objectForKey:@"magicNumber"];


If the object cannot be found, then it will return nil, as mentioned before, it is possible to send a message to nil, so when using a dictionary, you need to be aware of the problem of whether the object being fetched is empty. In addition, we can get the object by subscript access, but the content in the subscript should be the value of the key.


Variable dictionaries


As with several other classes, Apple's design approach is that the base class is immutable, and then provides you with a mutable subclass that has a variable version of Mutablensdictionary, which we can use to dynamically add or remove objects to the dictionary.


[dictionary setObject:@"another string" forKey:@"secondString"];[dictionary removeObjectForKey:@"anObject"];


In addition, for collection classes, they are initialized with nil as the end, so if we really need to insert a nil in the collection, then we have to pass in an object. Apple's position on nil is that there is no object, it's a special value, so it's not an actual object, so if we're going to pass in an empty object, we have to use the NSNull class to get an object, just like this:


NSArray *array = @[ @"string", @42, [NSNull null] ];
Using collections to complete data persistence


In general, after the data processing, there is always some data to be recorded, in iOS, we can through the file system, archiving, SQLite and coredata to achieve data persistence, here will not detail data persistence, Just illustrates the role that some of these collection classes can play in the persistence process.



Using Nsarray and nsdictionary for data persistence is simple, such as:


NSURL *fileURL = ...
NSArray *array = @[@"first", @"second", @"third"];

BOOL success = [array writeToURL:fileURL atomically:YES];
if (!success) {
    // an error occured...
}


Also, for files on disk, if the data objects they store are one of the attribute list types, then they can be converted directly from one file to the runtime object:


NSURL *fileURL = ...
NSArray *array = [NSArray arrayWithContentsOfURL:fileURL];
if (!array) {
    // an error occurred...
}


Finally, for the traversal of the collection class, we can use the for-in form for the collection classes provided by Apple, but for the dictionary, the variables in the for-in loop are key, so it's best to use a class that identifies different objects when defining the key. This makes it much easier to traverse.



Programming with Objective-c (Fri)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.