2015-06-22 52 views
0

我需要使用NSBlock作爲可以在JavaScript中進行更改的屬性。在JavaScriptCore中使用NSBlock作爲屬性

@protocol ExportingUser <NSObject, JSExport> 

@property (nonatomic, copy) void (^changedName) (void); 

@property (nonatomic) NSString* name; 

@end 

我基本上想從obj-C中調用changedName,它的定義來自JavaScript。就像這樣:

user.name = "Peyman"; // this will change the name property in the Obj-C as well. 

user.changedName = function() { console.log("yay"); } // but this doesn't 

我知道,這是有可能通過JSValue的callWithArguments方法,但如果可能的話,我更喜歡這種方法。

編輯:其實,我不認爲callWithArguments方法將工作。因爲綁定到Objective-C類的對象在JavaScript中不可擴展,所以引入新的字段可能會被忽略。

回答

0

正如JSValue.h上市:

// Objective-C type | JavaScript type 
// --------------------+--------------------- 
//   nil   |  undefined 
//  NSNull  |  null 
//  NSString  |  string 
//  NSNumber  | number, boolean 
//  NSDictionary | Object object 
//  NSArray  | Array object 
//  NSDate  |  Date object 
//  NSBlock *  | Function object * 
//   id **  | Wrapper object ** 
//  Class *** | Constructor object *** 
// 
// * Instances of NSBlock with supported arguments types will be presented to 
// JavaScript as a callable Function object. For more information on supported 
// argument types see JSExport.h. If a JavaScript Function originating from an 
// Objective-C block is converted back to an Objective-C object the block will 
// be returned. All other JavaScript functions will be converted in the same 
// manner as a JavaScript object of type Object. 

顯然,你可以逃脫:

@property (nonatomic, copy) JSValue* changedName; 

然後,當你想叫它:

typedef void (^nameChangedBlock)(void); 

nameChangedObject = [self.changedName toObject]; 

if ([nameChangedObject isKindOfClass: NSClassFromString(@"NSBlock")]){ 
    ((nameChangedBlock)nameChangedObject)(); 
}