загрузка в xib из plist с использованием сгруппированных таблиц - PullRequest
0 голосов
/ 08 августа 2011

Я новичок, работающий над приложением, у которого есть сгруппированное табличное представление, заполненное из списка.Каждая ячейка имеет изображение, заголовок и описание.Все это прекрасно работает.У меня также есть ключ контроллера в списке, который загружает контроллер представления и XIB.В настоящий момент для каждой выбранной ячейки загружается отдельный контроллер представления.Однако было бы неплохо загрузить тот же контроллер представления и xib, но просто заполнить переменные (изображение, текст и звуковой файл) из одного и того же списка.Может кто-нибудь помочь мне сделать это.это мой код

//  RootViewController.h
//  TableViewPush
//

#import <UIKit/UIKit.h>


@interface RootViewController :  UITableViewController <UITableViewDelegate, UITableViewDataSource>  {

    NSArray *tableDataSm;

}
- (IBAction)howToUse: (id) sender;  

@property (nonatomic, retain) NSArray *tableDataSm;


@end




//  RootViewController.m
//  TableViewPush
//

#import "RootViewController.h"
#import "Location One.h"
#import "HowToUseViewController.h"
#import "TableViewPushAppDelegate.h"


@implementation RootViewController 

@synthesize tableDataSm;


- (IBAction)howToUse: (id) sender;  
{
    HowToUseViewController *how = [[HowToUseViewController alloc] initWithNibName:@"HowToUse"  bundle:nil];
    [self.navigationController pushViewController:how animated:YES];
    [how release];
}
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"TableDataSm" ofType:@"plist"];
    self.tableDataSm = [NSArray arrayWithContentsOfFile:path];


    self.title = @"Studios";
}
/*
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
 */
#pragma mark -
#pragma mark Table view data source

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
    const NSDictionary *const sectionData = [self.tableDataSm objectAtIndex:section];
    return [sectionData objectForKey:@"header"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.tableDataSm count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    const NSDictionary *const data = [self.tableDataSm objectAtIndex:section];
    const NSArray *const rows = [data objectForKey:@"rows"];
    return [rows count];
}
- (NSDictionary *)rowForIndexPath:(NSIndexPath *)indexPath {
    const NSDictionary *const data = [self.tableDataSm objectAtIndex:indexPath.section];
    const NSArray *const rows = [data objectForKey:@"rows"];
    return [rows objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    const NSDictionary *const row = [self rowForIndexPath:indexPath];

    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [row objectForKey:@"text"];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

    cell.detailTextLabel.text = [row objectForKey:@"detailText"];
    // This assume the image file you specify exists in your bundle of course!
    NSString *imageFileName = [row objectForKey:@"image"];
    cell.imageView.image = [UIImage imageNamed:imageFileName];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    const NSDictionary *const row = [self rowForIndexPath:indexPath];

    NSString *wantedClassName = [row objectForKey:@"controller"];

    UIViewController *const vc = [[NSClassFromString (wantedClassName) alloc] init];
    NSLog(@"controller is -%@-", wantedClassName);
    [self.navigationController pushViewController:vc animated:YES];

    [vc release];  

}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {

    [super viewDidUnload];

    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}
- (void)dealloc {

    [super dealloc];
}


@end



//  Location One.h
//  TableViewPush
//

#import <UIKit/UIKit.h>
#import "RootViewController.h"
#import  <AVFoundation/AVAudioPlayer.h>
#import <AudioToolbox/AudioToolbox.h>


@interface   Location_One: UIViewController <AVAudioPlayerDelegate>  {


    AVAudioPlayer *theAudio;
}   

-(IBAction)pushButton;


-(IBAction)play;
-(IBAction)stop;
-(IBAction)pause;


@end





//  Location One.m
//  TableViewPush
//

#import "Location One.h"
#import "TableViewPushAppDelegate.h"
#import <AVFoundation/AVAudioPlayer.h>

@implementation Location_One



-(id) init{
    if((self = [super initWithNibName:@"Location One" bundle:nil])){

    }
    return self;
}


-(IBAction)pushButton  {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"AudioOne" ofType:@"mp3"];
    if (theAudio)[theAudio release];
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play];
}



-(IBAction)play {
    [theAudio play];
}
-(IBAction)stop {
    [theAudio stop];
}
-(IBAction)pause {
    [theAudio pause];
}

-(void)beginInterruption{
    [theAudio pause];

}

-(void)endInterruptionWithFlags{
    [theAudio play];
}




- (void)viewDidLoad {


    NSLog(@"InView did load");


    [super viewDidLoad];
    self.title = @"Glass Illusions Studio";
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {

    [theAudio release];

    [Location_One release];
    [super dealloc];
}


@end




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
     <dict>
          <key>header</key>
          <string>85710</string>
          <key>rows</key>
          <array>
               <dict>
                    <key>text</key>
                    <string>52 Glass Illusions Studio</string>
                    <key>detailText</key>
                    <string>150 S Camino Seco, #119</string>
                    <key>image</key>
                    <string>VisualFEight.png</string>
                    <key>controller</key>
                    <string>Location_One</string>
                    <key>picture</key>
                    <string>VisualOne.png</string>
                    <key>audio</key>
                    <string>AudioOne.mp3</string>
                    <key>description</key>
                    <string>TextOne</string>
               </dict>
               <dict>
                    <key>text</key>
                    <string>53 Illusions Gallery</string>
                    <key>detailText</key>
                    <string>150 S Camino Seco, #150</string>
                    <key>image</key>
                    <string>VisualFTen.png</string>
                    <key>controller</key>
                    <string>Location_One</string>
                     <key>picture</key>
                    <string>VisualTwo.png</string>
                    <key>audio</key>
                    <string>AudioTwo.mpg</string>
                    <key>description</key>
                    <string>TextTwo</string>
               </dict>
               <dict>
                    <key>text</key>
                    <string>54 Adam Noman Metal Sculpture</string>
                    <key>detailText</key>
                    <string>7208 E Paseo San Andres</string>
                    <key>image</key>
                    <string>VisualFEleven.png</string>
                    <key>controller</key>
                    <string>Location_One</string>
                     <key>picture</key>
                    <string>VisualThree.png</string>
                    <key>audio</key>
                    <string>AudioThree.mp3</string>
                    <key>description</key>
                    <string>TextThree</string>
               </dict>
               <dict>
                    <key>text</key>
                    <string>54 Firefly Glass Gallery</string>
                    <key>detailText</key>
                    <string>8002 E Broadway Blvd</string>
                    <key>image</key>
                    <string>VisualFSeven.png</string>
                    <key>controller</key>
                    <string>Location_One</string>
                     <key>picture</key>
                    <string>VisualFour.png</string>
                    <key>audio</key>
                    <string>AudioFour.mp3</string>
                    <key>description</key>
                    <string>TextFour</string>
               </dict>
                <dict>
                    <key>text</key>
                    <string>55 Red Door Studio</string>
                    <key>detailText</key>
                    <string>6323 E Printer Udell St.</string>
                    <key>image</key>
                    <string>VisualFFourteen.png</string>
                    <key>controller</key>
                    <string>Location_One</string>
                     <key>picture</key>
                    <string>VisualFive.png</string>
                    <key>audio</key>
                    <string>AudioFive.mp3</string>
                    <key>description</key>
                    <string>TextFive</string>
               </dict>
          </array>
     </dict>
     <dict>
          <key>header</key>
          <string>85711</string>
          <key>rows</key>
          <array>
               <dict>
                    <key>text</key>
                    <string>56 Fuente Y Claro</string>
                    <key>detailText</key>
                    <string>4001 E Montecito St.</string>
                    <key>image</key>
                    <string>VisualFFifteen.png</string>
                    <key>controller</key>
                    <string>Location_One</string>
                     <key>picture</key>
                    <string>VisualSix.png</string>
                    <key>audio</key>
                    <string>AudioSix.mp3</string>
                    <key>description</key>
                    <string>TextSix</string>
               </dict>
          </array>
     </dict>
</array>
</plist>

1 Ответ

0 голосов
/ 08 августа 2011

Это реализация управляемого данными шаблона для различных VC, которые загружаются при выборе разных ячеек. Я показал и реализацию LocationOne, и это можно использовать в качестве шаблона или суперкласса для новых VC Location. Я рекомендую вам внимательно изучить использование свойств для управления памятью членов данных (как я это делал в LocationOne). Это действительно делает управление памятью быстрым.

RootViewController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *const row = [self rowForIndexPath:indexPath];

    NSString *wantedClassName = [row objectForKey:@"controller"];

    UIViewController *const vc = [[[NSClassFromString (wantedClassName) alloc] autorelease]


    if ([vc isKindOfClass:[Location_One class]])
    {
        Location_One* loVC = (Location_One*)vc;
        loVC.myImage = [row objectForKey:@"picture"];
        loVC.myText = [row objectForKey:@"decription"];
        loVC.mySoundFile = [row objectForKey:@"audio"];
    }

    NSAssert(vc, @"viewController should exist!");

    [self.navigationController pushViewController:vc animated:YES];

    // There's no need to release the new VC because it is autoreleased 
}


// LocationOne.h
//

@interface   Location_One: UIViewController <AVAudioPlayerDelegate>  
{
    AVAudioPlayer *theAudio;
    NSString* myImage;
    NSString* myText;
    NSString* myAudio;
}   

@property (nonatomic, retain) AVAudioPlayer* theAudio;
@property (nonatomic, retain) NSString* myImage;
@property (nonatomic, retain) NSString* myText;
@property (nonatomic, retain) NSString* myAudio;

-(IBAction)pushButton;
-(IBAction)play;
-(IBAction)stop;
-(IBAction)pause;
@end


// LocationOne.m
//

#import "Location One.h"
#import "TableViewPushAppDelegate.h"
#import <AVFoundation/AVAudioPlayer.h>

@implementation Location_One

@synthesize theAudio;
@synthesize myImage;
@synthesize myText;
@synthesize myAudio;

-(IBAction)pushButton:(id)sender
{
    NSString *path = [[NSBundle mainBundle] pathForResource:myAudio ofType:@"mp3"];

    // theAudio is a property, therefore you can assigning it to self. will bump the retain count.
    // and decrement  the retain count for any previous audio players (releasing them).

    // Since an audio player can only set the URL at creation time, the create a new instance.
    // Using properties rather than just class members allows you to handle memory without explicit retains/releases
    self.theAudio = [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL] autorelease];
    self.theAudio.delegate = self;

}

-(IBAction)play {
    [theAudio play];
}

-(IBAction)stop {
    [theAudio stop];
}

-(IBAction)pause {
    [theAudio pause];
}

-(void)beginInterruption{
    [theAudio pause];    
}

-(void)endInterruptionWithFlags{
    [theAudio play];
}

- (void)viewDidLoad 
{
    [super viewDidLoad];
    self.title = @"Glass Illusions Studio";
}

- (void)viewDidUnload 
{
    [super viewDidUnload];
    // Only release theAudio when the view gets an unload message.
    // This is because it's recreated as needed.
    self.theAudio = nil;
}

- (void)dealloc 
{
    // I'm not sure why you were doing a self-retain or self-release but I 
    // suggest against it. Let the NavigationController handle the lifetime
    // of this object.
    // [Location_One release];

    self.theAudio = nil;
    self.myImage = nil;
    self.myText = nil;
    self.myAudio = nil;

    [super dealloc];
}

// This method is an older way of iOS handling memory shortages.
// You don't need it as long as you implement viewDidUnload.
// - (void)didReceiveMemoryWarning 

@end
...