[objective-c/cn] Adding Chinese translation for Objective-C

This commit is contained in:
Sven 2024-04-16 13:35:29 +08:00
parent 1baca665b8
commit bb12f92330

View File

@ -0,0 +1,754 @@
---
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Clayton Walker", "https://github.com/cwalk"]
- ["Fernando Valverde", "http://visualcosita.xyz"]
translators:
- ["Gaoang Chen", "https://github.com/chengaoang"]
filename: LearnObjectiveC-cn.m
lang: zh-cn
---
Objective-CObjective-C 2.0 macOS iOS Cocoa Cocoa Touch
C Smalltalk
```objective-c
// //
/*
*/
// Xcode 使 pragma mark
// ,便 Xcode编译器,
#pragma mark Navigation Functions // 跳转栏上新增标签 'Navigation Functions'
#pragma mark - Navigation Functions // 同样的标签,现在有一个分隔符
// 使 #import Foundation
// 使 <>
// 使 ""
#import <Foundation/Foundation.h>
#import "MyClass.h"
// Xcode 5 iOS >= 7.0 OS X >= 10.9 modules
@import Foundation;
// main
int main (int argc, const char * argv[])
{
// , init
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// 使ARC使 @autoreleasepool
@autoreleasepool {
// 使 NSLog
NSLog(@"Hello World!"); // "Hello World!"
///////////////////////////////////////
//
///////////////////////////////////////
//
int myPrimitive1 = 1;
long myPrimitive2 = 234554664565;
//
// *
MyClass *myObject1 = nil; //
id myObject2 = nil; //
// %@
// 'description'
NSLog(@"%@ and %@", myObject1, [myObject2 description]); // => "(null) and (null)"
//
NSString *worldString = @"World";
NSLog(@"Hello %@!", worldString); // => "Hello World!"
// NSMutableString NSString
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
[mutableString appendString:@" World!"];
NSLog(@"%@", mutableString); // => "Hello World!"
//
NSNumber *theLetterZNumber = @'Z';
char theLetterZ = [theLetterZNumber charValue]; // theLetterZ 'Z'
// NSNumber对象来进行转换
NSLog(@"%c", theLetterZ);
//
NSNumber *fortyTwoNumber = @42;
int fortyTwo = [fortyTwoNumber intValue]; // 42
NSLog(@"%i", fortyTwo);
NSNumber *fortyTwoUnsignedNumber = @42U;
unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // 42
NSLog(@"%u", fortyTwoUnsigned);
NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
short fortyTwoShort = [fortyTwoShortNumber shortValue]; // 42
NSLog(@"%hi", fortyTwoShort);
NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41];
unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // 41
NSLog(@"%u", fortyOneUnsigned);
NSNumber *fortyTwoLongNumber = @42L;
long fortyTwoLong = [fortyTwoLongNumber longValue]; // 42
NSLog(@"%li", fortyTwoLong);
NSNumber *fiftyThreeLongNumber = @53L;
unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // 53
NSLog(@"%lu", fiftyThreeUnsigned);
//
NSNumber *piFloatNumber = @3.141592654F;
float piFloat = [piFloatNumber floatValue]; // 3.141592654f
NSLog(@"%f", piFloat); // => 3.141592654
NSLog(@"%5.2f", piFloat); // => " 3.14"
NSNumber *piDoubleNumber = @3.1415926535;
double piDouble = [piDoubleNumber doubleValue]; // 3.1415926535
NSLog(@"%f", piDouble);
NSLog(@"%4.2f", piDouble); // => "3.14"
// NSDecimalNumber float double
NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
// NSDecimalNumber 使 +-*/
[oneDecNum decimalNumberByAdding:twoDecNum];
[oneDecNum decimalNumberBySubtracting:twoDecNum];
[oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
[oneDecNum decimalNumberByDividingBy:twoDecNum];
NSLog(@"%@", oneDecNum); // => 10.99 NSDecimalNumber
// BOOL
NSNumber *yesNumber = @YES;
NSNumber *noNumber = @NO;
//
BOOL yesBool = YES;
BOOL noBool = NO;
NSLog(@"%i", yesBool); // => 1
//
// Objective-C
NSArray *anArray = @[@1, @2, @3, @4];
NSNumber *thirdNumber = anArray[2];
NSLog(@"Third number = %@", thirdNumber); // => "Third number = 3"
// Xcode 7 NSArray 使
NSArray<NSString *> *stringArray = @[@"hello", @"world"];
// NSMutableArray NSArray
// 便 NSArray
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
[mutableArray addObject:@"Hello"];
[mutableArray addObject:@"World"];
[mutableArray removeObjectAtIndex:0];
NSLog(@"%@", [mutableArray objectAtIndex:0]); // => "World"
//
NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" };
NSObject *valueObject = aDictionary[@"A Key"];
NSLog(@"Object = %@", valueObject); // => "Object = (null)"
// Xcode 7 NSDictionary 使
NSDictionary<NSString *, NSNumber *> *numberDictionary = @{@"a": @1, @"b": @2};
// NSMutableDictionary 使
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2];
[mutableDictionary setObject:@"value1" forKey:@"key1"];
[mutableDictionary setObject:@"value2" forKey:@"key2"];
[mutableDictionary removeObjectForKey:@"key1"];
//
// [object mutableCopy] 使 [object copy] 使
NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
//
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
NSLog(@"%@", set); // => {(Hello, World)}
// Xcode 7 NSSet 使
NSSet<NSString *> *stringSet = [NSSet setWithObjects:@"hello", @"world", nil];
// NSMutableSet
NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2];
[mutableSet addObject:@"Hello"];
[mutableSet addObject:@"Hello"];
NSLog(@"%@", mutableSet); // => {(Hello)}
///////////////////////////////////////
//
///////////////////////////////////////
// 使 C
//
2 + 5; // => 7
4.2f + 5.1f; // => 9.3f
3 == 2; // => 0 (NO)
3 != 2; // => 1 (YES)
1 && 1; // => 1 ()
0 || 1; // => 1 ()
~0x0F; // => 0xF0 ()
0x0F & 0xF0; // => 0x00 ()
0x01 << 1; // => 0x02 (1 )
///////////////////////////////////////
//
///////////////////////////////////////
// If-Else
if (NO)
{
NSLog(@"I am never run");
} else if (0)
{
NSLog(@"I am also never run");
} else
{
NSLog(@"I print");
}
// Switch
switch (2)
{
case 0:
{
NSLog(@"I am never run");
} break;
case 1:
{
NSLog(@"I am also never run");
} break;
default:
{
NSLog(@"I print");
} break;
}
// While
int ii = 0;
while (ii < 4)
{
NSLog(@"%d,", ii++); // ii++ 使 ii ii 1
} // => "0,"
// "1,"
// "2,"
// "3,"
// For
int jj;
for (jj=0; jj < 4; jj++)
{
NSLog(@"%d,", jj);
} // => "0,"
// "1,"
// "2,"
// "3,"
// Foreach
NSArray *values = @[@0, @1, @2, @3];
for (NSNumber *value in values)
{
NSLog(@"%@,", value);
} // => "0,"
// "1,"
// "2,"
// "3,"
// Objective-C 使
for (id item in values) {
// Objective-C id
// C void * Objective-C id
NSLog(@"%@,", item);
} // => "0,"
// "1,"
// "2,"
// "3,"
// Try-Catch-Finally
@try
{
//
@throw [NSException exceptionWithName:@"FileNotFoundException"
reason:@"File Not Found on System" userInfo:nil];
} @catch (NSException * e) // 使@catch (id exceptionName)
{
NSLog(@"Exception: %@", e);
} @finally
{
NSLog(@"Finally. Time to clean up.");
} // => "Exception: File Not Found on System"
// "Finally. Time to clean up."
// NSError
NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil];
///////////////////////////////////////
//
///////////////////////////////////////
//
//
MyClass *myObject = [[MyClass alloc] init];
// Objective-C
// Objective-C
[myObject instanceMethodWithParameter:@"Steve Jobs"];
// 使
[pool drain];
// @autoreleasepool
}
//
return 0;
}
///////////////////////////////////////
//
///////////////////////////////////////
// MyClass.h
//
// @interface : <>
// {
// ; <=
// }
// @property ; <=
// -/+ () ; <=
// @end
@interface MyClass : NSObject <MyProtocol> // NSObject Objective-C
{
//
int count; // protected 访
@private id data; // 访便
NSString *name;
}
// 访 setter
// setter set @property
@property int propInt; // setter 'setPropInt'
@property (copy) id copyId; // (copy) =>
// (readonly) => @interface
@property (readonly) NSString *roString; // @implementation 使 @synthesize 访
// NSString
// getter setter 使set
@property (getter=lengthGet, setter=lengthSet:) int length;
//
+/- ():( *);
// +
+ (NSString *)classMethod;
+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight;
// -
- (NSString *)instanceMethodWithParameter:(NSString *)string;
- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number;
// 使
- (id)initWithDistance:(int)defaultDistance;
// Objective-C
@end //
// 访使 @property setter
// 'set' @property
MyClass *myClass = [[MyClass alloc] init]; // MyClass
[myClass setCount:10];
NSLog(@"%d", [myClass count]); // => 10
// 使 @interface getter setter
[myClass lengthSet:32];
NSLog(@"%i", [myClass lengthGet]); // => 32
// 便使使访
myClass.count = 45;
NSLog(@"%i", myClass.count); // => 45
//
NSString *classMethodString = [MyClass classMethod];
MyClass *classFromName = [MyClass myClassFromName:@"Hello"];
//
MyClass *myClass = [[MyClass alloc] init]; // MyClass
NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"];
//
//
//
// SEL @selector()
// methodAParameterAsString:andAParameterAsNumber: MyClass
SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
if ([myClass respondsToSelector:selectorVar]) { //
// performSelector
NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
[myClass performSelector:selectorVar withObject:arguments]; //
} else {
// NSStringFromSelector() NSString
NSLog(@"MyClass 不包含方法:%@", NSStringFromSelector(selectedVar));
}
//
@implementation MyClass
- (void)methodSignature:(NSString *)parameterName {
//
}
+ (NSString *)classMethod {
return @"一些字符串";
}
+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight {
height = defaultHeight;
return [[self alloc] init];
}
- (NSString *)instanceMethodWithParameter:(NSString *)string {
return @"新字符串";
}
- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number {
return @42;
}
//
// @implementation @interface
- (NSNumber *)secretPrivateMethod {
return @72;
}
[self secretPrivateMethod]; //
// MyProtocol
- (void)myProtocolMethod
{
//
}
@end //
///////////////////////////////////////
//
///////////////////////////////////////
//
//
//
// --
// -- Objective-C NSString
// --
//
// 使
// Car
@interface Car : NSObject
@property NSString *make;
@property NSString *color;
- (void)turnOn;
- (void)accelerate;
@end
// Car
#import "Car.h"
@implementation Car
@synthesize make = _make;
@synthesize color = _color;
- (void)turnOn {
NSLog(@"Car is on.");
}
- (void)accelerate {
NSLog(@"Accelerating.");
}
@end
// Truck Car Car
// Car
// @interface Car+Clean.hBaseClassName+CategoryName.h
#import "Car.h" // 确保导入基类以进行扩展。
@interface Car (Clean) //
- (void)washWindows; // Car
- (void)wax;
@end
// @implementation Car+Clean.mBaseClassName+CategoryName.m
#import "Car+Clean.h" // 导入 Clean 类别的 @interface 文件。
@implementation Car (Clean)
- (void)washWindows {
NSLog(@"Windows washed.");
}
- (void)wax {
NSLog(@"Waxed.");
}
@end
// Car 使
#import "Car+Clean.h" // 导入尽可能多的不同类别。
#import "Car.h" // 也需要导入基类以使用其原始功能。
int main (int argc, const char * argv[]) {
@autoreleasepool {
Car *mustang = [[Car alloc] init];
mustang.color = @"Red";
mustang.make = @"Ford";
[mustang turnOn]; // 使 Car
[mustang washWindows]; // 使 Car Clean
}
return 0;
}
// 使 Car @implementation
#import "Car+Clean.h" // 还记得,只导入 @interface 文件。
@implementation Car
- (void)lockCar {
NSLog(@"Car locked."); // Car 使 lockCar @interface
}
@end
///////////////////////////////////////
//
///////////////////////////////////////
// @interface访
// @interface : Shape.h
@interface Shape : NSObject // Shape
@property (readonly) NSNumber *numOfSides;
- (int)getNumOfSides;
@end
// numOfSides getNumOfSides
// @implementation filename: Shape.m (BaseClassName+CategoryName.m)
#import "Shape.h"
// @implementation
@interface Shape () // ()
@property (copy) NSNumber *numOfSides; // 使 numOfSides
-(NSNumber)getNumOfSides; // 使 getNumOfSides NSNumber int
-(void)privateMethod; //
@end
// @implementation
@implementation Shape
@synthesize numOfSides = _numOfSides;
-(NSNumber)getNumOfSides { // @implementation
return _numOfSides;
}
-(void)privateMethod {
NSLog(@"通过扩展创建的私有方法。Shape 实例无法调用我。");
}
@end
// Xcode 7.0
@interface Result<__covariant A> : NSObject
- (void)handleSuccess:(void(^)(A))success
failure:(void(^)(NSError *))failure;
@property (nonatomic) A object;
@end
//
Result<NSNumber *> *result;
Result<NSArray *> *result;
// Result
// 使 A
@interface Result : NSObject
- (void)handleSuccess:(void(^)(NSArray *))success
failure:(void(^)(NSError *))failure;
@property (nonatomic) NSArray * object;
@end
@interface Result : NSObject
- (void)handleSuccess:(void(^)(NSNumber *))success
failure:(void(^)(NSError *))failure;
@property (nonatomic) NSNumber * object;
@end
//
// Clang @implementations
// Result @implemnation
@implementation Result
- (void)handleSuccess:(void (^)(id))success
failure:(void (^)(NSError *))failure {
//
}
@end
///////////////////////////////////////
//
///////////////////////////////////////
//
//
// @protocol : "CarUtilities.h"
@protocol CarUtilities <NSObject> // <NSObject> =>
@property BOOL engineOn; // @synthesize @property
- (void)turnOnEngine; //
@end
//
#import "CarUtilities.h" // 导入协议文件。
@interface Car : NSObject <CarUtilities> // <>
// @property CarUtilities @implementation
- (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // 使
@end
// @implementation @property
@implementation Car : NSObject <CarUtilities>
@synthesize engineOn = _engineOn; // engineOn @property @synthesize
- (void)turnOnEngine { // turnOnEngine
_engineOn = YES; //
}
// 访
- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind {
[objectOfSomeKind engineOn]; // 访
[objectOfSomeKind turnOnEngine]; //
[objectOfSomeKind engineOn]; // YESNO
}
@end
// Car 访
Car *carInstance = [[Car alloc] init];
[carInstance setEngineOn:NO];
[carInstance turnOnEngine];
if ([carInstance engineOn]) {
NSLog(@"Car engine is on."); // => "Car engine is on."
}
// id
if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
NSLog(@"此处不运行,因为 MyClass 类没有实现 CarUtilities 协议。");
} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) {
NSLog(@"此处运行,因为 Car 类实现了 CarUtilities 协议。");
}
// @interface Car (CarCategory) <CarUtilities>
// @interface Car : NSObject <CarUtilities, CarCleaning>
//
#import "Brother.h"
@protocol Brother; //
@protocol Sister <NSObject>
- (void)beNiceToBrother:(id <Brother>)brother;
@end
// Sister Brother Brother Sister
#import "Sister.h"
@protocol Sister; //
@protocol Brother <NSObject>
- (void)beNiceToSister:(id <Sister>)sister;
@end
///////////////////////////////////////
//
///////////////////////////////////////
// 使使
// 4
^(int n) {
return n + 4;
}
int (^addUp)(int n); //
void (^noParameterBlockVar)(void); //
// 访
int outsideVar = 17; // addUp outsideVaroutsideVar 17
__block long mutableVar = 3; // __block 使 outsideVar
addUp = ^(int n) { // (int n)
NSLog(@"块可以有多行代码。");
NSSet *blockSet; //
mutableVar = 32; // __block
return n + outsideVar; //
}
int addUp = addUp(10 + 16); //
//
@implementation BlockExample : NSObject
- (void)runBlock:(void (^)(NSString))block {
NSLog(@"块参数不返回任何值,且接受一个 NSString 对象。");
block(@"传递给块的参数来执行。"); //
}
@end
///////////////////////////////////////
//
///////////////////////////////////////
/*
使使
Objective-C 使使
12使3
*/
MyClass *classVar = [MyClass alloc]; // 'alloc' classVar
[classVar release]; // classVar
// 'retain'
MyClass *newVar = [classVar retain]; // classVar newVar
[classVar autorelease]; // @autoreleasepool
// @property 使 'retain' 'assign' 便
@property (retain) MyClass *instance; //
@property (assign) NSSet *set; // /
// ARC
// Xcode 4.2 iOS 4 ARC
// ARC retainrelease autorelease使 ARC 使 retainrelease autorelease
MyClass *arcMyClass = [[MyClass alloc] init];
// ... 使 arcMyClass
// ARC使 arcMyClass [arcMyClass release] ARC release
// 'assign' 'retain' @property 使 'weak' 'strong'
@property (weak) MyClass *weakVar; // 'weak' weakVar nil
@property (strong) MyClass *strongVar; // 'strong' 使
// @property 使
__strong NSString *strongString; //
__weak NSSet *weakSet; // weakSet nil
__unsafe_unretained NSArray *unsafeArray; // __weak unsafeArray nil
```
## 进一步阅读
[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C)
[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf)
[Programming with Objective-C for iOS](https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html)
[Programming with Objective-C for Mac OSX](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html)
[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started)