Changeset 11810 for lang/objective-c

Show
Ignore:
Timestamp:
05/18/08 01:17:29 (5 years ago)
Author:
mootoh
Message:

separated Bookmark importer from application delegate.

Location:
lang/objective-c/HatebuCoreData
Files:
2 added
4 modified

Legend:

Unmodified
Added
Removed
  • lang/objective-c/HatebuCoreData/HatebuCoreData.xcodeproj/project.pbxproj

    r11796 r11810  
    2222                86FD38B80DDECE190016EAA6 /* TagCountTransformer.m in Sources */ = {isa = PBXBuildFile; fileRef = 860430910DDB0A4C007C1628 /* TagCountTransformer.m */; }; 
    2323                86FD38DF0DDED47F0016EAA6 /* UTManagedObjectContext.m in Sources */ = {isa = PBXBuildFile; fileRef = 86FD38DE0DDED47F0016EAA6 /* UTManagedObjectContext.m */; }; 
     24                86FD39460DDF369D0016EAA6 /* HatenaBookmark.m in Sources */ = {isa = PBXBuildFile; fileRef = 86FD383B0DDE073A0016EAA6 /* HatenaBookmark.m */; }; 
     25                86FD394D0DDF38590016EAA6 /* Importer.m in Sources */ = {isa = PBXBuildFile; fileRef = 86FD394C0DDF38590016EAA6 /* Importer.m */; }; 
     26                86FD394E0DDF39220016EAA6 /* Importer.m in Sources */ = {isa = PBXBuildFile; fileRef = 86FD394C0DDF38590016EAA6 /* Importer.m */; }; 
    2427                8D11072B0486CEB800E47090 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */; }; 
    2528                8D11072D0486CEB800E47090 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; settings = {ATTRIBUTES = (); }; }; 
     
    5659                86FD38DD0DDED47F0016EAA6 /* UTManagedObjectContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UTManagedObjectContext.h; sourceTree = "<group>"; }; 
    5760                86FD38DE0DDED47F0016EAA6 /* UTManagedObjectContext.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = UTManagedObjectContext.m; sourceTree = "<group>"; }; 
     61                86FD394B0DDF38590016EAA6 /* Importer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Importer.h; sourceTree = "<group>"; }; 
     62                86FD394C0DDF38590016EAA6 /* Importer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Importer.m; sourceTree = "<group>"; }; 
    5863                8D1107310486CEB800E47090 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; }; 
    5964                8D1107320486CEB800E47090 /* HatebuCoreData.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HatebuCoreData.app; sourceTree = BUILT_PRODUCTS_DIR; }; 
     
    97102                                86FD38DD0DDED47F0016EAA6 /* UTManagedObjectContext.h */, 
    98103                                86FD38DE0DDED47F0016EAA6 /* UTManagedObjectContext.m */, 
     104                                86FD394B0DDF38590016EAA6 /* Importer.h */, 
     105                                86FD394C0DDF38590016EAA6 /* Importer.m */, 
    99106                        ); 
    100107                        name = Classes; 
     
    293300                                86FD38B80DDECE190016EAA6 /* TagCountTransformer.m in Sources */, 
    294301                                86FD38DF0DDED47F0016EAA6 /* UTManagedObjectContext.m in Sources */, 
     302                                86FD394D0DDF38590016EAA6 /* Importer.m in Sources */, 
    295303                        ); 
    296304                        runOnlyForDeploymentPostprocessing = 0; 
     
    306314                                8609DD8F0DDC0DF300E2B4DD /* BookmarkController.m in Sources */, 
    307315                                8698C85D0DDD60B800294DC6 /* Bookmark.m in Sources */, 
     316                                86FD39460DDF369D0016EAA6 /* HatenaBookmark.m in Sources */, 
     317                                86FD394E0DDF39220016EAA6 /* Importer.m in Sources */, 
    308318                        ); 
    309319                        runOnlyForDeploymentPostprocessing = 0; 
  • lang/objective-c/HatebuCoreData/HatebuCoreData_AppDelegate.h

    r11652 r11810  
    2424 
    2525- (IBAction)saveAction:sender; 
    26 - (void)addSome:(NSString *)filename; 
    2726- (IBAction)openFile:sender; 
    2827- (void)openUrl:(NSArray *)url; 
    2928@end 
     29// vim:set ft=objc: 
  • lang/objective-c/HatebuCoreData/HatebuCoreData_AppDelegate.m

    r11796 r11810  
    99#import "HatebuCoreData_AppDelegate.h" 
    1010#import "TagCountTransformer.h" 
     11#import "Importer.h" 
    1112 
    1213@implementation HatebuCoreData_AppDelegate 
    1314 
    1415/** 
    15  Returns the support folder for the application, used to store the Core Data 
    16  store file.  This code uses a folder named "HatebuCoreData" for 
    17  the content, either in the NSApplicationSupportDirectory location or (if the 
    18  former cannot be found), the system's temporary directory. 
     16  Returns the support folder for the application, used to store the Core Data 
     17  store file.  This code uses a folder named "HatebuCoreData" for 
     18  the content, either in the NSApplicationSupportDirectory location or (if the 
     19  former cannot be found), the system's temporary directory. 
    1920 */ 
    2021- (NSString *)applicationSupportFolder { 
    21    
    22     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); 
    23     NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory(); 
    24     return [basePath stringByAppendingPathComponent:@"HatebuCoreData"]; 
     22  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); 
     23  NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory(); 
     24  return [basePath stringByAppendingPathComponent:@"HatebuCoreData"]; 
    2525} 
    2626 
    2727/** 
    28  Creates, retains, and returns the managed object model for the application  
    29  by merging all of the models found in the application bundle. 
     28  Creates, retains, and returns the managed object model for the application  
     29  by merging all of the models found in the application bundle. 
    3030 */ 
    3131- (NSManagedObjectModel *)managedObjectModel { 
    32    
    33     if (managedObjectModel != nil) { 
    34         return managedObjectModel; 
    35     } 
    36    
    37     managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];     
     32  if (managedObjectModel != nil) 
     33    return managedObjectModel; 
    3834 
    39   NSAssert([managedObjectModel entities] != nil, @"entities should not be nil"); 
    40   NSLog(@"NSManagedObjectModel(UnitTest).inMemoryMOCForTesting : %d", [[managedObjectModel entities] count]); 
    41  
    42     return managedObjectModel; 
    43 } 
    44  
    45  
    46 /** 
    47  Returns the persistent store coordinator for the application.  This  
    48  implementation will create and return a coordinator, having added the  
    49  store for the application to it.  (The folder for the store is created,  
    50  if necessary.) 
    51  */ 
    52 - (NSPersistentStoreCoordinator *) persistentStoreCoordinator { 
    53    
    54     if (persistentStoreCoordinator != nil) { 
    55         return persistentStoreCoordinator; 
    56     } 
    57    
    58     NSFileManager *fileManager; 
    59     NSString *applicationSupportFolder = nil; 
    60     NSURL *url; 
    61     NSError *error; 
    62      
    63     fileManager = [NSFileManager defaultManager]; 
    64     applicationSupportFolder = [self applicationSupportFolder]; 
    65     if ( ![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL] ) { 
    66         [fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil]; 
    67     } 
    68      
    69     url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: @"HatebuCoreData.xml"]]; 
    70     persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]]; 
    71     if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error]){ 
    72         [[NSApplication sharedApplication] presentError:error]; 
    73     }     
    74    
    75     return persistentStoreCoordinator; 
     35  managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];     
     36  return managedObjectModel; 
    7637} 
    7738 
    7839/** 
    79  Returns the managed object context for the application (which is already 
    80  bound to the persistent store coordinator for the application.)  
     40  Returns the persistent store coordinator for the application.  This  
     41  implementation will create and return a coordinator, having added the  
     42  store for the application to it.  (The folder for the store is created,  
     43  if necessary.) 
    8144 */ 
    82 - (NSManagedObjectContext *) managedObjectContext { 
    83    
    84     if (managedObjectContext != nil) { 
    85         return managedObjectContext; 
    86     } 
    87    
    88     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 
    89     if (coordinator != nil) { 
    90         managedObjectContext = [[NSManagedObjectContext alloc] init]; 
    91         [managedObjectContext setPersistentStoreCoordinator: coordinator]; 
    92     } 
    93      
    94     return managedObjectContext; 
     45- (NSPersistentStoreCoordinator *) persistentStoreCoordinator { 
     46  if (persistentStoreCoordinator != nil) 
     47    return persistentStoreCoordinator; 
     48 
     49  NSFileManager *fileManager = [NSFileManager defaultManager]; 
     50  NSString *applicationSupportFolder = [self applicationSupportFolder]; 
     51  if (![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL]) 
     52    [fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil]; 
     53 
     54  NSURL *url = [NSURL fileURLWithPath: 
     55    [applicationSupportFolder stringByAppendingPathComponent: @"HatebuCoreData.xml"]]; 
     56  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] 
     57    initWithManagedObjectModel: [self managedObjectModel]]; 
     58 
     59  NSError *error; 
     60  if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType 
     61      configuration:nil URL:url options:nil error:&error]) 
     62    [[NSApplication sharedApplication] presentError:error]; 
     63 
     64  return persistentStoreCoordinator; 
    9565} 
    9666 
    9767/** 
    98  Returns the NSUndoManager for the application.  In this case, the manager 
    99  returned is that of the managed object context for the application. 
     68  Returns the managed object context for the application (which is already 
     69  bound to the persistent store coordinator for the application.)  
    10070 */ 
    101 - (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window { 
    102     return [[self managedObjectContext] undoManager]; 
     71- (NSManagedObjectContext *) managedObjectContext { 
     72  if (managedObjectContext != nil) 
     73    return managedObjectContext; 
     74 
     75  NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 
     76  if (coordinator != nil) { 
     77    managedObjectContext = [[NSManagedObjectContext alloc] init]; 
     78    [managedObjectContext setPersistentStoreCoordinator: coordinator]; 
     79  } 
     80 
     81  return managedObjectContext; 
    10382} 
    10483 
    10584/** 
    106  Performs the save action for the application, which is to send the save: 
    107  message to the application's managed object context.  Any encountered errors 
    108  are presented to the user. 
     85  Returns the NSUndoManager for the application.  In this case, the manager 
     86  returned is that of the managed object context for the application. 
     87 */ 
     88- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window { 
     89  return [[self managedObjectContext] undoManager]; 
     90} 
     91 
     92/** 
     93  Performs the save action for the application, which is to send the save: 
     94  message to the application's managed object context.  Any encountered errors 
     95  are presented to the user. 
    10996 */ 
    11097- (IBAction) saveAction:(id)sender { 
    111    
    112     NSError *error = nil; 
    113     if (![[self managedObjectContext] save:&error]) { 
    114         [[NSApplication sharedApplication] presentError:error]; 
    115     } 
     98  NSError *error = nil; 
     99  if (![[self managedObjectContext] save:&error]) 
     100    [[NSApplication sharedApplication] presentError:error]; 
    116101} 
    117102 
     103/** 
     104  Implementation of the applicationShouldTerminate: method, used here to 
     105  handle the saving of changes in the application managed object context 
     106  before the application terminates. 
     107 */ 
     108- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender { 
     109  int reply = NSTerminateNow; 
     110 
     111  if (managedObjectContext != nil) 
     112    if ([managedObjectContext commitEditing]) { 
     113      NSError *error; 
     114      if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 
     115 
     116        // This error handling simply presents error information in a panel with an  
     117        // "Ok" button, which does not include any attempt at error recovery (meaning,  
     118        // attempting to fix the error.)  As a result, this implementation will  
     119        // present the information to the user and then follow up with a panel asking  
     120        // if the user wishes to "Quit Anyway", without saving the changes. 
     121 
     122        // Typically, this process should be altered to include application-specific  
     123        // recovery steps.   
     124 
     125        BOOL errorResult = [[NSApplication sharedApplication] presentError:error]; 
     126        if (errorResult == YES) 
     127          reply = NSTerminateCancel; 
     128        else { 
     129          int alertReturn = NSRunAlertPanel(nil, 
     130            @"Could not save changes while quitting. Quit anyway?", 
     131            @"Quit anyway", @"Cancel", nil); 
     132          if (alertReturn == NSAlertAlternateReturn) 
     133            reply = NSTerminateCancel;   
     134        } 
     135      } 
     136    }  
     137    else 
     138      reply = NSTerminateCancel; 
     139 
     140  return reply; 
     141} 
    118142 
    119143/** 
    120  Implementation of the applicationShouldTerminate: method, used here to 
    121  handle the saving of changes in the application managed object context 
    122  before the application terminates. 
     144  Implementation of dealloc, to release the retained variables. 
    123145 */ 
    124 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender { 
    125    
    126     NSError *error; 
    127     int reply = NSTerminateNow; 
    128      
    129     if (managedObjectContext != nil) { 
    130         if ([managedObjectContext commitEditing]) { 
    131             if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 
    132          
    133                 // This error handling simply presents error information in a panel with an  
    134                 // "Ok" button, which does not include any attempt at error recovery (meaning,  
    135                 // attempting to fix the error.)  As a result, this implementation will  
    136                 // present the information to the user and then follow up with a panel asking  
    137                 // if the user wishes to "Quit Anyway", without saving the changes. 
    138          
    139                 // Typically, this process should be altered to include application-specific  
    140                 // recovery steps.   
    141          
    142                 BOOL errorResult = [[NSApplication sharedApplication] presentError:error]; 
    143          
    144                 if (errorResult == YES) { 
    145                     reply = NSTerminateCancel; 
    146                 }  
    147          
    148                 else { 
    149            
    150                     int alertReturn = NSRunAlertPanel(nil, @"Could not save changes while quitting. Quit anyway?" , @"Quit anyway", @"Cancel", nil); 
    151                     if (alertReturn == NSAlertAlternateReturn) { 
    152                         reply = NSTerminateCancel;   
    153                     } 
    154                 } 
    155             } 
    156         }  
    157         else { 
    158             reply = NSTerminateCancel; 
    159         } 
    160     } 
    161  
    162     return reply; 
     146- (void) dealloc { 
     147  [managedObjectContext release], managedObjectContext = nil; 
     148  [persistentStoreCoordinator release], persistentStoreCoordinator = nil; 
     149  [managedObjectModel release], managedObjectModel = nil; 
     150  [super dealloc]; 
    163151} 
    164152 
    165  
    166 /** 
    167  Implementation of dealloc, to release the retained variables. 
    168  */ 
    169 - (void) dealloc { 
    170     [managedObjectContext release], managedObjectContext = nil; 
    171     [persistentStoreCoordinator release], persistentStoreCoordinator = nil; 
    172     [managedObjectModel release], managedObjectModel = nil; 
    173     [super dealloc]; 
    174 } 
    175  
    176 - (void)addEntry:(NSXMLElement *)entry { 
    177   NSManagedObject *bmk = [NSEntityDescription 
    178     insertNewObjectForEntityForName:@"Bookmark" 
    179              inManagedObjectContext:[self managedObjectContext]]; 
    180  
    181   NSString *title = [[[entry elementsForName: @"title"] objectAtIndex:0] stringValue]; 
    182   NSLog(@"title = %@", title); 
    183   [bmk setValue:title forKey:@"title"]; 
    184  
    185   NSArray *urls = [entry elementsForName:@"link"]; 
    186   for (NSXMLElement *url in urls) { 
    187     if ([[[url attributeForName:@"rel"] stringValue] compare:@"related"]) { 
    188       NSString *siteUrl = [[url attributeForName:@"href"] stringValue]; 
    189       NSLog(@"siteUrl = %@", siteUrl); 
    190       [bmk setValue:siteUrl forKey:@"siteUrl"]; 
    191     } else { 
    192       NSString *bookmarkUrl = [[url attributeForName:@"href"] stringValue]; 
    193       NSLog(@"bookmarkUrl = %@", bookmarkUrl); 
    194       [bmk setValue:bookmarkUrl forKey:@"bookmarkUrl"]; 
    195     } 
    196   } 
    197  
    198   NSString *issued = [[[entry elementsForName: @"issued"] objectAtIndex:0] stringValue]; 
    199   issued = [issued stringByReplacingOccurrencesOfString:@"T" withString:@" "]; 
    200   issued = [issued stringByReplacingOccurrencesOfString:@"+" withString:@" +"]; 
    201   // issued = [issued stringByReplacingOccurrencesOfString:@"-" withString:@" -"]; // XXX BUG: won't work outside of Japan (Timezone +09:00) 
    202   NSDate *date = [NSDate dateWithString:issued]; 
    203   NSLog(@"issued: %@", issued); 
    204   [bmk setValue:date forKey:@"issued"]; 
    205   NSString *body = [[[entry elementsForName: @"summary"] objectAtIndex:0] stringValue]; 
    206   NSLog(@"body: %@", body); 
    207   [bmk setValue:body forKey:@"body"]; 
    208    
    209   NSMutableSet *tag_set = [[NSMutableSet alloc] init]; 
    210   NSLog(@"tag_set: %@", tag_set); 
    211   NSArray *tags = [entry elementsForName:@"dc:subject"]; 
    212   NSLog(@"tags: %@", tags); 
    213  
    214   for (NSXMLElement *t in tags) { 
    215     NSString *name = [t stringValue]; 
    216  
    217     NSPredicate *pred = [NSPredicate predicateWithFormat:@"name == %@", name]; 
    218     NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tag" inManagedObjectContext:[self managedObjectContext]]; 
    219  
    220     NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
    221     [request setEntity:entity]; 
    222     [request setPredicate:pred]; 
    223  
    224     NSManagedObject *tag; 
    225  
    226     if (0 < [[self managedObjectContext] countForFetchRequest:request error:nil]) { // tag already exists 
    227       NSArray *arr = [[self managedObjectContext] executeFetchRequest:request error:nil]; 
    228       tag = [arr objectAtIndex:0]; 
    229     } else { 
    230       tag = [NSEntityDescription insertNewObjectForEntityForName:@"Tag" inManagedObjectContext:[self managedObjectContext]]; 
    231       [tag setValue:name forKey:@"name"]; 
    232     } 
    233     [tag_set addObject:tag]; 
    234     NSLog(@"added: %@", tag); 
    235   } 
    236   [bmk setValue:tag_set forKey:@"tags"]; 
    237 } 
    238  
    239 - (void)addEntries:(NSArray *)ary { 
    240   [progressbar_ setMaxValue:[ary count]]; 
    241   int i = 0; 
    242   for (NSXMLElement *entry in ary) { 
    243     [progressbar_ setDoubleValue:i]; 
    244     [self addEntry:entry]; 
    245     i++; 
    246   } 
    247 } 
    248  
    249 - (void)addSome:(NSString *)filepath { 
    250   NSURL *url = [NSURL fileURLWithPath:filepath]; 
    251   NSError *err; 
    252   NSXMLDocument *doc = [[NSXMLDocument alloc] initWithContentsOfURL:url options:NSXMLDocumentTidyXML error:&err];  
    253   NSArray *ary = [[doc rootElement] nodesForXPath: @"/feed/entry" error: &err]; 
    254   NSLog(@"%d", [ary count]); 
    255  
    256   //[self performSelectorInBackground:@selector(addEntries:) withObject:ary]; 
    257   [self addEntries:ary]; 
    258 } 
    259153 
    260154- (IBAction)openFile:sender { 
     
    263157 
    264158  if (NSOKButton == [opanel runModalForDirectory:NSHomeDirectory() 
    265                         file:nil 
    266                        types:fileTypes]) { 
    267     NSLog([opanel filename]); 
    268     [self addSome:[opanel filename]]; 
    269   }else{ 
    270     NSLog(@"Cancel"); 
     159      file:nil 
     160      types:fileTypes]) { 
     161    Importer *importer = [[[Importer alloc] initWithContext:[self managedObjectContext]] autorelease]; 
     162    [importer importFromFile:[opanel filename]]; 
    271163  } 
    272164} 
    273165 
     166/** 
     167 * add transformers. 
     168 */ 
    274169- (void)applicationDidFinishLaunching:(NSNotification *)ntf { 
    275170  id transformer = [[[TagCountTransformer alloc] initWithContext:[self managedObjectContext]] autorelease]; 
    276171  [NSValueTransformer  
    277    setValueTransformer:transformer  
    278    forName:@"TagCountTransformer"]; 
     172    setValueTransformer:transformer  
     173    forName:@"TagCountTransformer"]; 
    279174} 
    280175 
    281  
     176/** 
     177 * open selected url in browser. 
     178 */ 
    282179- (void)openUrl:(NSArray *)urls { 
    283   NSLog(@"openUrl : %@", [urls objectAtIndex:0]); 
    284180  NSURL *url = [NSURL URLWithString:[urls objectAtIndex:0]]; 
    285181  NSArray *arr = [NSArray arrayWithObject:url]; 
  • lang/objective-c/HatebuCoreData/HatenaBookmark.m

    r11714 r11810  
    1313 
    1414-(void) update { 
    15   NSLog(@"Bookmark(Hatena)#update: %@", self); 
     15  //NSLog(@"Bookmark(Hatena)#update: %@", self); 
    1616} 
    1717