加载iOS上的NSBundle文件

27

我想创建一个具有非常灵活的图形用户界面(可换肤)的项目。为了实现这一点,我想从外部资源(例如网站)加载一个NSBundle。该bundle应包含与主项目中的某些属性和方法(IBOutlets和IBActions)相对应的nibs。

似乎苹果公司限制了使用NSBundle的可能性。是否有任何方法可以让这个工作?如果不能以传统的方式实现,有什么推荐的替代方案吗?

2个回答

34

如承诺的一样,这里有一个简短的说明,介绍我是如何让它正常工作的。

在我的AppDelegate中,我检查服务器上是否有一个新的bundle(打包在zip文件中)。如果存在,我会下载bundle。该bundle包含我需要的可皮肤图形界面的nibs和其他相关数据(例如图形文件)。代码看起来有些像这样:

TestAppDelegate.m

- (void)downloadBundle 
{      
   NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/~wsc/template.bundle.zip"];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLResponse *response = nil;
   NSError *error = nil;
   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
   NSLog(@"%d", [httpResponse statusCode]);

   if ([httpResponse statusCode] == 404) // bundle will be deleted and the default interface will be used ...
   {
      NSString *path = [documentsDirectory stringByAppendingPathComponent:@"template.bundle"];
      [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
      return;
   }
   else if (error) 
   {
      NSLog(@"%@", error);
   }

   BOOL didWriteData = [data writeToFile:zipFile atomically:YES];
   if (didWriteData) 
   {
      BOOL success = [SSZipArchive unzipFileAtPath:zipFile toDestination:documentsDirectory];
      if (!success) 
      {
         NSLog(@"failed to unzip file.");
      }
   }
}

请注意,我使用了由neoneye建议的SSZipArchive类。需要将bundle打包到某种容器中以高效地下载所有内容,因为bundle只是遵循Apple约定的目录和文件结构。

我的其中一个类是一个具有标签和按钮作为IBOutlets的ViewController。 ViewController中最重要的代码如下:

TestViewController.h

@interface TestViewController : UIViewController {
   UIButton *button;
   UILabel *label;
}

@property (nonatomic, retain) IBOutlet UIButton *button;
@property (nonatomic, retain) IBOutlet UILabel *label;

- (IBAction)buttonTouched:(id)sender;

@end

TestViewController.m

@implementation TestViewController
@synthesize button, label;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

// the -init method is overridden to use nib file from bundle, if bundle exists ...
- (id)init 
{
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *file = [documentsDirectory stringByAppendingPathComponent:@"template.bundle"];
   NSBundle *bundle = [NSBundle bundleWithPath:file];
   if (!bundle)
   {
      NSLog(@"no bundle found, falling back to default gui ...");
      return [self initWithNibName:nil bundle:nil];
   }

   NSString *nibName = NSStringFromClass([self class]);
   return [self initWithNibName:nibName bundle:bundle];
}

- (void)dealloc
{
   [button release];
   [label release];
   [view release];

   [super dealloc];
}

#pragma mark - View lifecycle

- (void)loadView
{
   if (self.nibName && self.nibBundle) 
   {
      // connect outlets to proxy objects ...
      NSDictionary *objects = [NSDictionary dictionaryWithObjectsAndKeys:
          self.label, @"label", 
          self.button, @"button", 
          nil];
      NSDictionary *proxies = [NSDictionary dictionaryWithObject:objects forKey:UINibExternalObjects];
      NSArray *nibs = [self.nibBundle loadNibNamed:self.nibName owner:self options:proxies]; // connection happens here ...

      NSLog(@"nibs found with name %@: %d", self.nibName, [nibs count]);
      return;
   }

   // show default gui if no nib was found ...

   CGRect frame = [UIScreen mainScreen].applicationFrame;
   self.view = [[[UIView alloc] initWithFrame:frame] autorelease];
   [self.view setBackgroundColor:[UIColor lightGrayColor]];

   self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   [self.button setFrame:CGRectMake(0.0f, 0.0f, 60.0f, 30.0f)];
   [self.button setCenter:CGPointMake(160.0f, 100.0f)];
   [self.button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
   [self.view addSubview:self.button];

   self.label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 30.0f)] autorelease];
   [self.label setCenter:CGPointMake(160.0f, 50.0f)];
   [self.label setTextAlignment:UITextAlignmentCenter];
   [self.view addSubview:self.label];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
   [super viewDidLoad];

   // for my purposes I'll add the localized string from the mainBundle here for the standard controls, 
   // this will override the text set in the nibs, since the nibs are loaded and displayed at this point ...
   [self.button setTitle:NSLocalizedString(@"TestButton", nil) forState:UIControlStateNormal];
   [self.label setText:NSLocalizedString(@"TestLabel", nil)];

}

- (void)viewDidUnload
{
   [super viewDidUnload];
   self.button = nil;
   self.label = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -

- (IBAction)buttonTouched:(id)sender 
{
   [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DialogTitle", nil) 
                                message:NSLocalizedString(@"ButtonTouchedText", nil) 
                               delegate:nil 
                      cancelButtonTitle:@"OK" 
                      otherButtonTitles:nil] 
     autorelease] show];
}

@end
实际的笔尖被定义在一个单独的链接项目中(Cocoa NSBundle 项目,有些参数被改变以使其适用于 iOS 设备)。文件的所有者是 TestViewController,所以我可以访问所有的插座和操作,并建立适当的连接。请注意,在 TestViewController 中没有定义 view (UIView *)属性,因为超类已经有了 view 属性。确保在界面构建器中连接视图。还要注意,nib 文件使用与实际类相同的名称以便使用。

在网上找不到太多关于如何做到这一点的信息,所以我希望这对于许多有类似目标的人都有所帮助。


如果我在下载的版本中连接了插座,那么我是否需要像在loadView()中一样重新应用它们呢?谢谢! - Mark
哇!感谢您的快速回复!我会尽快尝试并反馈结果。再次感谢!!! - Mark
你有这个示例项目托管在任何地方吗?那也可能会有所帮助。 :) - Mark
谢谢!希望这能帮助我找出我做错了什么! - Mark
1
明白了!感谢你的帮助,Wolfgang!我发现如果在编译捆绑包之前连接操作,它们会被保留。看起来IBOutlets没有同样的好处。总的来说,这是一个不错的获取“可定制”UI的方法。再次感谢!干杯! - Mark
显示剩余11条评论

12

未经测试。

您可以将所有内容打包成 zip 文件,使用 SSZipArchive 解压缩。

NSBundle* bundle = [NSBundle bundleWithPath:absolutePathToNibFile].

UIViewController* vc = [[[MyViewController alloc] initWithNibName:@"mycustomnib" bundle:bundle] autorelease];

好了,我终于通过将NSBundle从finder复制到iPhone模拟器文件夹中来加载documentsDirectory中的NSBundle,所以在真实设备上应该也能正常工作。要从服务器上实际复制文件似乎需要将bundle归档为zip文件,所以我会接受你的答案。编辑:一旦我让所有东西都正常运行,我将在此主题中发布完整的代码。 - Wolfgang Schreurs
我使用了SSZipArchive来分发HTML内容,它似乎是一个相当强大的组件。它可以在iPhone 3上提取非常大的zip文件(我测试过的文件大小约为40 MB),而不会耗尽内存。 - neoneye

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接