2014-09-28 26 views
0

我正在使用存儲在NSUserDefaults中的書籤跟蹤文件的位置,以便如果用戶決定移動它,我的應用仍然可以訪問它。我創建在目標C中檢測帶有書籤的已刪除文件

- (NSData *)bookmarkFromURL:(NSURL *)url { 
NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationMinimalBookmark 
       includingResourceValuesForKeys:NULL 
            relativeToURL:NULL 
              error:NULL]; 
return bookmark; 
} 
每次我需要的文件我從檢索NSUserDefaults的書籤和我一起

- (NSURL *)urlFromBookmark:(NSData *)bookmark { 
NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark 
             options:NSURLBookmarkResolutionWithoutUI 
           relativeToURL:NULL 
          bookmarkDataIsStale:NULL 
             error:NULL]; 
return url; 
} 

它的工作原理就像一個魅力解決NSURL

初始書籤。我想要的唯一附加功能是能夠檢測用戶是否刪除了該文件。當然,我可以定期檢查NSURL是否返回零,但我希望馬上通知。我怎樣才能做到這一點?

回答

1

你會希望使用NSNotification來檢測書籤何時被刪除,然後我想保存到NSUserDefaults。

在類中可以刪除書籤的東西,

-(void)deleteBookmark:(NSData*)bkmark{ 
    [[NSNotificationCenter defaultCenter]postNotificationName:@"XXBookmarkDeletedNotification" object:nil]; 
    } 

然後設置另一個類來偵聽通知並響應它。

// Setup the notification when the object is initialised or view is loaded. 
    -(void)setupNotifications{ 
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleBookmarkDeletedNotification:) name:@"XXBookmarkDeletedNotification" object:nil]; 
    } 

-(void)handleBookmarkDeletedNotification:(NSNotification*)notification{ 
// do whatever you need to do here, for example set a "deleted" flag in NSUserDefaults 
} 

// You to need to remove your class from the list of observers when you are done. 
-(void)removeNotifications{ 
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"XXBookmarkDeletedNotification" object:nil]; 
    }