Objective-C comparative learning

Source: Internet
Author: User
Tags uicontrol

When we learn a new language, we always compare it with the familiar language to learn it, just like when we learn English, we must remember the Chinese meaning of words, to help us understand and remember words.

The following compares Objective-C with C #. First, we will compare the language definition:
Objective-C, usually written in ObjC and rarely used in Objective C or Obj-C, is a programming language based on C and expanded with object-oriented features.
Currently, Objective-C is mainly used in the NeXTSTEP derivation systems Mac OS X and iOS, and is a basic language in NeXTSTEP and OpenStep. Objective-C can be compiled on any platform supported by gcc, because gcc supports Objective-C locally.
C # is an advanced object-oriented programming language based on the. NET Framework launched by Microsoft. C # is derived from C language and C ++ and inherits its powerful performance. It also uses the. NET Framework class library as the foundation and has the fast development capability similar to Visual Basic.

Objective-C adds the object-oriented feature to C, while C # is derived from C and C ++. It can be seen that C # is more advanced.

1. Objective-C is a strict superset of C
2. Single inheritance
3. Protocols define behavior that cross classes
4. Dynamic runtime
5. Loosely typed
 
1. C # is completely new and has no superset.
2. Single inheritance.
3. It feels like the interface of C.
4. It should be relative to the C language. Unlike the link method, ObjC uses the message-passing Method for method calling.
5. Loosely should be used to define and pass variables with objects in C.

Message Expression

[reciever message][reciever message:argument][reciever message:argument andArg:arg2]Metho definition- (void)castBallot;- (int)arg;- (void)setArg:(int)age;- (void)registerForState:(NSString*)state party:(NSString*)party;

For C # developers, this code looks strange. Don't be nervous. Think of it as a method call.

Objective-C 2.0 introduced dot syntax

float height = [persion height];float height = persion.height;[persion setHeight:newHeight];persion.height = newHeight;[[persion child] setHeight:newHeight];persion.child.height = newHeight;

Maybe it's because ObjC doesn't look so "weird", and it looks "normal" at last ~!

id anObject;Persion  *aPersion = (Persion *)anObject;


This is called "Loosely typed". id should be a pointer to an object.

Nil

if(persion == nil) return;if(!persion) return;persion = nil;[button setTarget: nil];persion = nil;[persion castBallot];


Nil is null in C #. The difference is that there is no error in calling the nil method in OjbC. It can be understood against the mesage-passing method. No one receives the message, then nothing will be done.

When ObjC was developed, C has no boolean type (C99 introduced one ).
ObjC uses a typedef to define BOOL as a type

BOOL flag = NO;


OjbC does not have the bool type. It usually uses YES and NO. You can also use TRUE and FALSE, or simply use 0 and 1.

SEL

SEL action = [button action];[button setAction:@selector(start:)];Conceptually similar to function pointer- (void)setName:(NSString*)name age:(int)age;SEL sel = @selector(setName:age:);


It feels like a delegate in C ).

Class:

Class myClass = [myObject class];NSLog(@"My class is %@", [myObject className]);if ([myObject isKindOfClass:[UIControl class]]){ // something}if ([myObject isMemberOfClass:[NSString class]]){ // someting string specific}

C # has Type. The above code is as follows in C:

Type myClass = myObject.GetType();Console.WriteLine(string.Format("My class is {0}", myClass.TypeName));if(myObject.GetType() == typeof(UIControl)){  // something}if (myObject is typeof(String)){ // someting string specific}

Identity versus Equality

Identity-testing equality of the pointer values

if (object1 == ojbect2){  NSLog(@"Same exact object instance");}

Equality-testing object attributes

if ([object1 isEqual: object2]){  NSLog(@"Logically equivalent, but may be different object instances");}

In C #, it seems that there is no function to directly compare object attribute values. You have to use your own override Equals method.

Description:

- (NSString*)description;[NSString stringWithFormat: @"The answer is: %@", myObject];NSLog([anObject description]);

Is this the ToString () method of the object ?!

NSObject

Is equal to the Object class in C.

NSString

In C constant strings are
"Simple"
In ObjC constant strings are
@ "Just as simple"

NSString *aString = @"Hello World!";NSLog(@"I am a %@, I have %d items", [array className], [array count]);NSString *myString = @"Hello";NSString *fullString;fullString = [myString stringByAppendString:@" world!"];

FullString wocould be set to "Hello World! ".

- (BOOL) isEqualToString:(NSStirng*)string;- (BOOL) hasPrefix:(NSString*)string;- (int)intValue;- (double)doubleValue;


Basically, there is nothing to say. This is System. Stirng.

Common NSMutableString methods:

+ (id)string;- (void)appendString:(NSString*)string;- (void)appendFormat:(NSString*)format, ...;

Example:

NSMutableString *newString = [NSMutableString string];[newString appendString:@"Hi"];[newString appendFormat:@" , my favorite number is: %d", [self favoriteNumber]];

Is it like StringBuilder?

Collections
Array, Dictionary, Set

Common NSArray methods:

+ arrayWithObjects:(id)firstObj, ...; //nil terminated!!!- (unsigned)count;- (id)objectAtIndex:(unsigned)index;- (unsigned)indexOfObject:(id)object;

NSNotFound returned for index if not found

if ([array indexOfObject:@"Purple"] == NSNotFound){  NSLog(@"No color purple");}

Isn't NSNotFound-1 ?!

NSMutableArray
NSMutalbeArray subclasses NSArray.

Common NSDictionary methods:

+ dictionaryWithObjectsAndKeys:(id)firstObject, ...;- (unsigned)count;- (id)objectForKey:(id)key;

Nil returned if no object found for gived key.
NSMutalbeDictionary
NSMutalbeDictionary subclasses NSDictionary.

Common NSSet methods:

+ setWithOjbects:(id)firstObj, ...; //nil terminated- (unsigned)count;- (BOOL)containsObject:(id)object;

No object is ever in there more than once.

NSMutableSet
NSMutableSet subclasses NSSet

C # It seems that there is no such thing as Set. Why is there no impression ?! However, it seems that it is not very troublesome.

Enumeration

for (Persion *persion in array){     NSLog([persion description]);}

C # foreach is correct.

Common NSNumber methods:

+ (NSNumber*)numberWithInt:(int)value;+ (NSNumber*)numberWithDouble:(double)value;- (int)intValue;- (double)doubleValue;


NSData/NSMutableData
NSDate/NSMutableDate

Byte [] and DateTime are correct.

Class interface declared in header file

#import <Foundation/Foundation.h>@interface Persion : NSObject{  // instance variables  NSString *name;  int arg;   }// method declarations- (NSString *)name;- (void)setName:(NSString *)value;- (int)age;- (void)setAge:(int)age;- (BOOL)canLegallyVote;- (void)castBallot;@end

Class Implementation write in. m file

#import "Persion.h"@implemetation Person- (int)age{  return age;}- (void)setAge:(int)value{  age = value;}// ... and other methods- (BOOL)canLegallyVote{  return ([self age] >= 18);}- (void)castBallot{  if([self canLegallyVote])  {    // do voting stuff  }  else  {    NSLog(@"I'm not allowed to vote!");  }}@end


I still feel that a class and a file are concise.

SuperClass methods

- (void)doSomething{  // Call superclass implementation first  [super doSometing];  // Then do our custom behavior  int foo = bar;  // ...}


ObjC super equals to C # base

Object Creation
+ Alloc
Class method that knows how much memory is needed.
-Init
Instance method to set initial values, perfomr other setup.

Create = Allocate + Initialize

Persion *persion = nil;Persion *persion = [[Persion alloc] init];


Isn't it a new object ?! Still doing this ??!!!

Implementing your own-init method

#import "Persion.h"@implementation Person- (id)init{  // allow superclass to initialize its state first  if (self == [super init])  {     age = 0;     name = @"Bob";     // do other initialization...  }   return self;}@end

Multiple init methods

- (id)init;- (id)initWithName:(NSString *)name;- (id)initWithNameAndAge:(NSString *)name age:(int)age;

Less specific ones typically call more specific with default values

- (id)init{  return [self initWithName:@"No Name"];}- (id)initWithName:(NSString *)name{  return [self initWithNameAndAge:name age:0];}
Persion *persion = [[Persion alloc] init];// ...[persion release]; // Object is deallocated[persion doSomething]; // Crash!persion = nil;[persion doSomething]; // No effect

Implementing a-dealloc method

#import "Persion.h"@implementation Persion- (void)dealloc{  // Do any cleanup that's necessary  // ...  [name release];  // when we're done, call super to clean us up  [super dealloc];}@end

Constructor and destructor.

Object Ownership

#import "Persion.h"@implementation Persion- (NSString *)name{  return name;}// retain- (void)setName:(NSString *)newName{  if (name != newName) {  [name release];  name = [newName retain];  // name's retain count has been bumped up by 1 }}// copy- (void)setName:(NSString *)newName{  if (name != newName) {  [name release];  name = [newName retain];  // name's retain count has been bumped up by 1 }}

Returning a newly created object

- (NSString *)fullName{  NSString *result;  result = [[NSString alloc] initWithFormat:@"%@ %@", firstName, lastName];  [result autorelease];  return result;}

Autorelease is not garbage collection, Objective-C on iPhone OS does not have garbage collection.

The GC of C # is advantageous. This is also an "advanced" aspect!

Defining Properites

@property int age;@property (copy) NSString *name;@property (readonly) BOOL canLegallyVote;

Synthesizing Properties

- (int)age{  return age;}- (void)setAge:(int)value{  age = value;}- (NSString *)name{  return name;}- (void)setName:(NSString *)value{  if(value != name)  {     [name release];     name = [value copy];  }}
@implementation Person@synthesize age;@synthesize name;- (BOOL)canLegallyVote{ return (age > 17);}

Memory namagement policies

@property (assign) NSString *name; // pointer assignment@property (retain) NSString *name; // retain called@property (copy) NSString *name; // copy called

Property Names vs. Instance Variables

@interface Persion : NSObject{  int numberOfYearsOld;}@property int age;@end
@implemetation Persion@synthesize age = numberOfYearsOld;@end

That is, there is nothing to say about property.

Method type identifier
Class Method: +
Instance method :-

The + of ObjC is equal to the static value in C #, but ObjC does not have public or private values.

Reference learning materials:

Http://v.163.com/special/opencourse/iphonekaifa.html

Http://rotator.youkulabs.com /? F5527199o1p0

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.