2013-05-02 61 views
1

我想在Objective-C中實現America's Cup數據流API的庫,並且正在環顧四周是否已經存在一個庫,並發現了一個implementation in C#,我發現它很漂亮,想借用一些想法從。這是我見過的第一個C#源代碼,所以我不完全理解發生了什麼。在Objective-C中實現C#事件

以下是使用C#庫的示例程序。它啓動一個處理網絡通信的客戶端和一個負責消息分派的FeedEvents。然後會發生一些有趣的事情,看起來像一個lambda表達式被用來指定OnChatterText發生時的動作,對嗎?我如何在Objective-C中做到這一點?使用塊?

class Program 
{ 
    static void Main(string[] args) 
    { 
     var c = new Client(); 
     var e = new FeedEvents(); 
     e.OnChatterText += ch => Console.WriteLine(string.Format("{0}: {1}", 
      ch.Source, ch.Text)); 

     c.OnMessage += e.MessageHandler; 
     c.Connect(); 

     Thread.Sleep(Timeout.Infinite); 
    } 
} 

回答

1

這裏是類似於你在你的問題,寫在objc指定的方法: Supposably我們有一類客戶端和FeedEvents。客戶端類實現爲處理 網絡連接(例如,使用AFNetworking)。 FeedEvents與Client類互連以處理來自網絡的事件,但這些事件必須調用「client」代碼塊來簡化操作。

@interface Client : NSObject 

- (void)connect; 

@end 

typedef void (^EventBlock) (id someData); 

@interface FeedEvents : NSObject 

@property (nonatomic, strong) EventBlock eventBlock; 

@end 

@interface ProgramClass : NSObject 

- (void)fetchEvents; 

@end 

@implementation ProgramClass 

- (void)fetchEvents { 
    // I prefer using singleton for generic instances that are used through entire application 
    // in the same way, but also sometimes it's better to use this approach: 
    // ... 

    Client *connectionClient = [Client new]; // or custom -[+[ alloc] initWithParameters...]; 
    FeedEvents *eventListener = [FeedEvents new]; // or custom -[+[ alloc] initWithParameters...]; 
    eventListener.eventBlock = ^(id someData) { 
     // do some additional configuration 
    }; 

    // using background queue to connect to some host 
    // but this is only for purpose of the method translation, because 
    // AFNetworking provides very reach background API 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, kNilOptions), ^{ 

     [connectionClient connect]; 
    }; 
} 

@end 

你也可以繼承的NSOperation使用此 - (空)主{}方法,在你的榜樣,並在後臺線程完全運行。

在這個示例代碼中,您應該知道塊參數等存在一些內存管理問題。對於您來說,在這種情況下更簡單的方法是將子操作NSOperation並在後臺運行,如here

希望這有幫助

+0

想想我明白了,謝謝! :) – ihatetoregister 2013-05-03 09:20:32

+0

很高興我能幫到你 – 2013-05-03 09:25:14