From C # To Object C, gradually learn the differences between Apple Development (2) -- Object C and C #

Source: Internet
Author: User
Tags float double

This series mainly introduces a series of thoughts and experiences from C # development on a Windows platform to Apple development on a Mac platform. This series of articles is gradually accumulated in the initial stage, we hope to provide you with a better and more real experience on the conversion process. In the previous article "from C # To Object C, I learned Apple development step by step (1) -- prepare the Development Account and development environment" and introduced some basic conversion insights and preparations, we have not yet officially introduced the differences between Object C and C #. We know that we will make some comparisons and understandings when converting from one environment or one language to another, in this way, the knowledge of our minds can be easily connected. In the context of the growing popularity of all things, we believe that all language features are the same. 1. Object-oriented Class 1) class definition Object C (hereinafter referred to as OC) and C # are both object-oriented languages, although OC is older than C # And originated from C, however, many features are very similar to C #. The extension method introduced in C #3.0 also exists in OC. Both OC and C # are the same. Their inherited relationships are single inheritance, and they are not as complex as the multi-inheritance of c ++, an important requirement of OC is to completely separate interfaces and implementations. This is the idea that developers familiar with C # must switch over. In OC, write a class, write the interface definition first and then write the implementation. Its syntax is very different from that of C #, but it is easy to understand. The keywords of OC are generally marked with the @ symbol, which is different from the default reserved keywords of C #. The @ interface, @ property, and @ keywords are usually displayed in XCode of the latest version, it was really amazing. It contained a lot of syntactic sugar, which is basically the same as C #. This will continue to be introduced in object initialization. Put the OC class definition in the. h file, and implement it in the. m file. below is the class interface declaration. @ Interface SimpleClass: NSObject @ end. The implementation operations of the class are as follows. # Import "SimpleClass. h" @ implementation SimpleClass @ end is just a demo class concept. Generally, classes have attributes or methods, so you need to add many more things. In addition, the comparison between OC and C # does not involve the namespace concept. In order to avoid confusion, OC classes are generally distinguished by prefixes. For example, many IOS basic class libraries with NS, UI, CA, and so on. 2) The method definition is as follows: the interface declares a method. The method definition @ interface XYZPerson: NSObject-(void) sayHello; @ end we can see that the above method definition (interface definition) it is very simple. Here there is a-symbol used to identify the method that belongs to the instance, and there is also a method that belongs to the class level, marked with the + symbol, this plus sign, similar to the static keyword in C #, the instance method defined as-by default is similar to the public method in C. This definition is the identifier of the return value. C # Is the void that does not require parentheses and does not return values. The method must be identified by brackets at the end. -(Void) sayHello; no parameter is defined for this method. Therefore, this OC is very interesting if the method has multiple parameters, I think this is the most personalized part of OC. If the method is as follows:-(void) setCaption: (NSString *) input; Class methods are called through spaces, and C # calls through vertices, this is also different, OC is referenced by spaces in a [], as shown below. [Object method]; [object methodWithInput: input]; The sayHello method just defined may be called in the following way: [self setCaption: @ "Default Caption"]; if the method is defined as multiple parameters (also called multiple parameters), the definition is as follows. -(Void) setNumerator: (int) n andDenominator: (int) d; then the call of the method is very interesting. [Frac2 setNumerator: 1 andDenominator: 5]; if there are more parameters, this method is always used. This is a bit close to reading habits. 3) After defining the parameters, define the methods and use them. We will introduce the attribute definitions in the class. We know that the attribute definitions in C # are very simple, such as public string Name {get; set. this can be defined in the interface definition of h. @ Property NSString * firstName; @ property NSString * lastName; then, in the Implementation class code, add the corresponding code @ synthesize keyword @ synthesize firstName, lastName; attribute can also be specified as read-only, as shown in the following code @ property (readonly) NSString * fullName; in addition, we need to be clear that the attribute is thread-safe by default, that is, atomic, it also has a Strong type of Strong. @ Interface XYZObject: NSObject @ property NSObject * implicitAtomicObject; // atomic by default @ property (atomic) NSObject * explicitAtomicObject; // explicitly marked atomic @ end is in many places, when using an attribute, we do not need to specify its thread security feature because it is more efficient. The general attribute definition code is as follows. @ Property (strong, nonatomic) IBOutlet UILabel * lblName; @ property (strong, nonatomic) IBOutlet UITextField * txtInput; should all attributes be specified as Strong, which is definitely not, another type of strong is weak, which indicates the weak type. The Strong type and the weak type are mainly for ARC. It is the scope of reference count, and strong is equivalent to the original retain. In general, in order to avoid the problem of mutual reference caused by some strong object attributes, there are also some object attributes such as UITable in the proxy class and data source object, their attribute definitions must be specified as weak. 2. The object type and initialization work in C #. We know that it contains some basic types (Primitive type) and some encapsulated object types, for example, its basic types include string int char float long double decimal and so on. Its corresponding packaging types include String Int32 Char Single Int64 Double Decimal. In OC, the basic types of OC are inherited from the basic types of C language, including basic types such as int float double char, there are also many reference types (or packaging types) Starting with NS, such as NSString NSNumber NSDate NSData NSValue, and so on. Many Collection types such as NSArray NSMutableArray NSDictionary need to add reference type objects. In addition, similar to the Object of C # Or the type specified by the dynamic type keyword dynamic, OC contains an id type, which is an uncertain type, it can be regarded as a weak definition of any type. The id type is a unique data type. In terms of concept, similar to the java Object class, it can be converted to any data type. In other words, the id type variable can store any data type object. In terms of internal processing, this type is defined as a pointer to an object, which is actually a pointer to the instance variable of this object. Note that id is a pointer, so you do not need to add a star number when using id. For example, id foo = nil; 1) We know the initialization of class objects, many of the OC initialization methods are through alloc init, as shown in the following code. XYZObject * object = [[XYZObject alloc] init]; in C #, most of them use the new method for initialization. In fact, the same can be done in the OC using the new method, however, only the default constructor method is used. The following code is equivalent to the preceding statement. XYZObject * object = [XYZObject new]; however, it seems that many people are used to initializing objects in the first way. 2) I believe many people believe that when using OC for String initialization, the first most impressive thing I think may be the NSString class. This is a bit similar to the String of C, all are fixed string objects. If you need to change the type of string objects, StringBuffer can be used in C #, while NSMutalbeString and NSMutableString can be used in OC, it can dynamically Add a string to delete a string, insert a string at a specified position, and use it to operate the string more flexibly. The definition and initialization of strings are simple. We can initialize them in the following way. NSString * someString = @ "Hello, World! "; We know that C # can also assign values using the @ character. Although it is generally used in the case of multiple rows, but in the OC, this @ character cannot be omitted. Many other data types are initialized using the @ character. This @ character can be very powerful, and it can be said to be a good syntactic sugar, for example, the following code initializes various types (in OC, NSNumber can be placed in any reference type) NSNumber * myBOOL = @ YES; NSNumber * myFloat = @ 3.14f; NSNumber * myInt = @ 42; NSNumber * myLong = @ 42L; The NSNumber type can be attached to various types, and can also be converted to other corresponding types, copy the code int scalarMagic = [magicNumber intValue]; unsigned int scalarUnsigned = [unsignedNumber unsignedIntValue]; long scalarLong = [longNumber longValue]; BOOL scala RBool = [boolNumber boolValue]; float scalarSimpleFloat = [simpleFloat floatValue]; double scalarBetterDouble = [betterDouble doubleValue]; char scalarChar = [someChar charValue]; copy the code, because an id type is introduced in OC, it can be considered to be equivalent to the dynamic type introduced in C #3.0. It can determine whether an object has a certain method at runtime, instead of being forcibly specified during compilation. The following code is compiled, and errors may occur during running. Id someObject = @ "Hello, World! "; [SomeObject removeAllObjects]; during compilation, the system does not check whether its object has the removeAllObject interface method because someObjec specifies the dynamic type of id, therefore, the compiler will not check its methods. 3) initialization of object sets the initialization of various types such as strings is introduced above. Many use powerful keywords @ for initialization. This syntactic sugar reduces a lot of tedious method calls, this is especially true for the initialization of collections. If you use the traditional set definition method, the following method is generally used. NSArray * someArray = [NSArray arrayWithObjects: someObject, someString, someNumber, someValue, nil]; add nil to the set, in the field of C #, you do not need to add such an identifier. In Object C, if you want to construct it through the arrayWithObjects method, you must add something like this, tell it that this is the end. If you put this in the second place, the constructed set has only two objects, which is strange. If you use a powerful @ method to construct a structure, everything is similar to C #. Here you can only admire its magic. NSArray * someArray = @ [firstObject, secondObject, thirdObject]; for example, the following defines a set of strings. NSArray * unsortedStrings = @ [@ "gammaString", @ "alphaString", @ "betaString"]; in C #, we often use dictionary objects, which are very convenient. Of course, there will certainly be something like this in OC. After all, many languages support it. This dictionary type is also a set type. Its traditional construction method is as follows: NSDictionary * dictionary = [NSDictionary dictionaryWithObjectsAndKeys: someObject, @ "anObject", @ "Hello, World! ", @" HelloString ", @ 42, @" magicNumber ", someValue, @" aValue ", nil]; it looks weird. Add instructions to follow the object, key is added in this way. This is very different from the habit of using C #, and it also carries a nil tail. If @ constructor is used, everything is cleaned up. It is stored in key and value mode, and nil is not needed. If nil is added, errors will occur. NSDictionary * dictionary =@ {@ "anObject": someObject, @ "helloString": @ "Hello, World! ", @" MagicNumber ": @ 42, @" aValue ": someValue}; in a collection, if an object is taken, use the following method to obtain NSNumber * storedNumber = [dictionary objectForKey: @ "magicNumber"]; you can also obtain NSNumber * storedNumber = dictionary [@ "magicNumber"] By subscript. If it is a general array set, you can obtain it through the following method, this method is similar to c. 1 NSNumber * storedNumber = array [0]; due to time and space issues, we will continue to introduce the features of OC compared with C, OC also involves many related features, such as extension methods, protocols (similar interfaces), code blocks, and various usage features of XCode.

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.