1. 程式人生 > >Object-C之簡單知識點

Object-C之簡單知識點

接iossdk中用到的

目錄

0.基本的語法

0.基本物件型別

1. 類:介面和實現,例項方法和類方法,變數和屬性

 

1.Category——擴充套件已有的類

2.區別檔案型別.h .m .mm 


0.基本的語法

0.基本物件型別

NSString   不可變字串   NSString *gameID = @"1111111"; 
NSNumber 數字物件。把整型、單精度、雙精度、字元型等基礎型別儲存為物件。  NSNumber *number = [NSNumber numberWithInt:123];
NSDictionary 由鍵-物件對組成的資料集合

NSDictionary *callbackDict =

@{@"state_code":[NSNumber numberWithInt:400],
     @"message":@"InitSuc"};

使用的特殊語法建立。

ps:Objective-C中的基本型別和C語言中的基本型別一樣.主要有:int,long,float,double,char,void, bool等

1. 類:介面和實現,例項方法和類方法,變數和屬性

@interface MyClass:NSObject{ 
// 類變數宣告
    // 成員變數及成員變數的可見範圍(訪問範圍)。
    @private // 私有的,只有自己可以訪問,還有 @public @protect 和c++一樣
    NSString *_name;

    @package // 在這個專案中都可以訪問
    NSString *_number;
}
// 類屬性宣告
//訪問區別:
// 屬性:可以使用‘.’符號訪問相當於 setter,getter方法。self.name
// 變數:可以使用指標訪問 self->name .也可以使用‘.’訪問,需要新增對應的屬性和@synthesize name =  _name;
@property (nonatomic, strong) NSString *name;

// - :表示例項方法
// -(returnType)methodName:(typeName) variable1 :(typeName)variable2;
// 呼叫使用例項物件訪問
// [self calculateAreaForRectangleWithLength:30 andBreadth:20];
-(void)calculateAreaForRectangleWithLength:(CGfloat)length andBreadth:(CGfloat)breadth;
- (void)sayHi;

// + :表示類方法
// 它可以通過使用類名訪問
// [MyClass simpleClassMethod];
+(void)simpleClassMethod;

// 單例 
// [[MyClass shareInstance] calculateAreaForRectangleWithLength:30 andBreadth:20];
+ (instancetype _Nullable )shareInstance;
@end
@implementation MyClass
// 類方法定義
- (void)sayHi{
    // 屬性和變數的訪問方式
    NSString *name = self.name;
    NSString *nameOne = self->_name;
    NSLog(@"Hello World!");
}
@end

 

1.Category——擴充套件已有的類

用來增加新行為或覆蓋舊的行為。

習慣:給類新增一個category,一般應該是新增一個資料夾。

例子:比如對UIView類,對 touchesBegan 進行重寫,category

即為VideoPlay

UIView+VideoPlay.h
#import <UIKit/UIKit.h>

@interface UIView (VideoPlay)

@end
UIView+VideoPlay.m
#import "UIView+VideoPlay.h"

// 在 m中需要呼叫別的檔案中的函式,需要用extern進行宣告該函式需要到外部去找。
extern void UnityStopFullScreenVideoIfPlaying();
extern int UnityIsFullScreenPlaying();
@implementation UIView (VideoPlay)
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent: (UIEvent*)event
{
    [super touchesBegan: touches withEvent: event];
    NSString *version = [UIDevice currentDevice].systemVersion;
    if(version.doubleValue >= 11 && UnityIsFullScreenPlaying())
    {
        UnityStopFullScreenVideoIfPlaying();
    }
}
@end

 

 

2.區別檔案型別.h .m .mm 

h :標頭檔案。標頭檔案包含一些宣告。  .

m :原始檔。可以包含Objective-C和C程式碼。(如上面的 UIView+VideoPlay.m )  

.mm :原始檔。除了可以包含Objective-C和C程式碼以外還可以包含C++程式碼。(.m 和.mm 的區別是告訴gcc 在編譯時要加的一些引數。所以.mm也可以命名成.m,只不過在編譯時要手動加引數(麻煩))

 

習慣:僅在你的Objective-C程式碼中確實需要使用C++類或者特性的時候才將原始檔命名為.mm

.mm 使用場景:Unity使用C#作為開發語言,IOS使用Object-c作為開發語言,為了讓C#呼叫OC程式碼,使用C/C++作為橋樑,因為OC和Object-C都支援直接嵌入C/C++。

例子:XXXSDKWrapper.mm 。XXXSDKManager.h 是用IOS寫的庫的標頭檔案,為了讓Unity呼叫這個庫中的函式,封裝一個C介面。extern “C”就是C++程式碼,所以應該用mm。

#import "XXXSdkWrapper.h"
#import "UnityAppController.h"
#import "UnityInterface.h"
#import "XXXSDKManager.h"
@implementation XXXSdkWrapper
@end

// 實現一個字串拷貝的函式
char* MakeStringCopy(const char* string)
{
    if (string == NULL)
        return NULL;
    
    char* res = (char*)malloc(strlen(string) + 1);
    strcpy(res, string);
    return res;
}
extern "C" {
    void XXXsdk_init()
    {
        [[XXXSDKManager shareInstance] initWithGameID:@"1111111" channelID:@"111" aID:@"111111111111111" andRootVC:UnityGetGLViewController()];
        // 字典--》NSData--》NSString
        NSDictionary *callbackDict = @{@"state_code":[NSNumber numberWithInt:123],
                                       @"message":@"InitSuc"};
        NSData *callbackData = [NSJSONSerialization dataWithJSONObject:callbackDict options:NSJSONWritingPrettyPrinted error:nil];
        NSString *callbackString = [[NSString alloc] initWithData:callbackData encoding:NSUTF8StringEncoding];
        UnitySendMessage("xxxsdk_cb_obj", "onInitSucCallBackWithjsonParam", [callbackString UTF8String]);
        
    }
    char* XXXsdk_channelId()
    {
        return MakeStringCopy("111");  
    }
    void XXXsdk_login()
    {
        [[XXXSDKManager shareInstance] loginWithCallBack:^(NSString * _Nullable session_id, NSString * _Nullable account_id) {
            NSDictionary *callbackDict = @{@"account_id":account_id,
                                            @"data":@{@"validateInfo":session_id,
                                                        @"opcode":@"11111",
                                                        @"channel_id":@"111"
                                                    }
                                               
                                            };
            NSData *callbackData = [NSJSONSerialization dataWithJSONObject:callbackDict options:NSJSONWritingPrettyPrinted error:nil];
            NSString *callbackString = [[NSString alloc] initWithData:callbackData encoding:NSUTF8StringEncoding];
            UnitySendMessage("xxxsdk_cb_obj", "onLoginSucCallBackWithjsonParam", [callbackString UTF8String]);
        }];
    }
    void XXXsdk_payWithOrderParams(const char* serverId , const char* roleId, const char* roleName, const char* gameOrder, const char* sum, const char* productId , const char* extend_params)
    {
        NSDictionary *orderParams = @{
                                      @"server_id" : [NSString stringWithUTF8String:serverId],
                                      @"role_id"   : [NSString stringWithUTF8String:roleId],
                                      @"role_name" : [NSString stringWithUTF8String:roleName],
                                      @"game_order" : [NSString stringWithUTF8String:gameOrder],
                                      @"real_price" : [NSString stringWithUTF8String:sum],
                                      @"product_id" : [NSString stringWithUTF8String:productId],
                                      @"ext" : [NSString stringWithUTF8String:extend_params]
                                      };
        [[XXXSDKManager shareInstance] payWithOrderParams:orderParams withPayCallBlock:^(NSInteger resultCode, NSString * _Nullable resultMsg) {
            if (resultCode == 1111) {
                NSLog(@"%@", resultMsg); // 內購成功
            } else if (resultCode == 1112) {
                NSLog(@"%@", resultMsg); // 網頁支付成功(頁面關閉)
            } else if (resultCode == 1113) {
                NSLog(@"%@", resultMsg); // 支付失敗
            }
        }];
    }
}