Search Results

Search found 774 results on 31 pages for 'singleton'.

Page 10/31 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Using a singleton database class in functions and multiple scripts(PHP) - best use methods

    - by dscher
    I have a singleton db connection which I get with: $dbConnect = myDatabase::getInstance(); which is easy enough. My question is what is the least rhetorical and legitimate way of using this connection in functions and classes? It seems silly to have to declare the variable global, pass it into every single function, and/or recreate this variable within every function. Is there another answer for this? Obviously I'm a noob and I can work my way around this problem 10 different ways, none of which is really attractive to me. It would be a lot easier if I could have that $dbConnect variable accessible in any function without needing to declare it global or pass it in. I do know I can add the variable to the $_SERVER array...is there something wrong with doing this? It seems somewhat inappropriate to me. Another quick question: Is it bad practice to do this: $result = myDatabase::getInstance()-query($query); from directly within a function?

    Read the article

  • which scope should a DAO typically have.

    - by Andreas Petersson
    its out of question that a dao will not hold any state. however, for easiest access to the class, is it better to use prototype( = new every time) or singleton? simple object creation is cheap for dao's.. it typically only holds a sessionfactory, accessing the object from a list of singletons may be equally expensive. clarfication: the focus of this question is, if there is a common convention to the scoping of daos.

    Read the article

  • How long will an ASP.NET MVC application run

    - by Christoph
    I wonder how long will an ASP.NET (MVC) application run, when no new requests come in? Lets say I'm using an IOC Container ans have a Singleton Object serving to the clients. As far as I know it will serve different page requests. But how long will it live when no new request come in? Is there any timeout (maybe configured through IIS) that says when my app will shut down?

    Read the article

  • What is so bad about Singletons

    - by Ewan Makepeace
    The Singleton pattern is a fully paid up member of the GoF Patterns Book but lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for Factory classes, and while you have to be a bit careful about multithreading issues (like any class actually) fail to see why they are so awful. This site especially seems to assume that everyone agrees that Singletons are evil. Why?

    Read the article

  • Zend_Registry - Do you need getInstance() ?

    - by Jesse
    Hey I'm wondering when accessing Zend_Registry in an application if you need to include getInstance() and if so, why? for example Zend_Registry::getInstance()-get('db'); vs. Zend_Registry::get('db'); they both seem to work with the later being less verbose. I vaguely understand that Zend_Registry is a singleton, which I think means there can only be one instance of it? so why would you need getInstance()?

    Read the article

  • Java 1.4 singleton containing a mutable field

    - by Philippe
    Hi, I'm working on a legacy Java 1.4 project, and I have a factory that instantiates a csv file parser as a singleton. In my csv file parser, however, I have a HashSet that will store objects created from each line of my CSV file. All that will be used by a web application, and users will be uploading CSV files, possibly concurrently. Now my question is : what is the best way to prevent my list of objects to be modified by 2 users ? So far, I'm doing the following : final class MyParser { private File csvFile = null; private static Set myObjects = Collections.synchronizedSet(new HashSet); public synchronized void setFile(File file) { this.csvFile = file; } public void parse() FileReader fr = null; try { fr = new FileReader(csvFile); synchronized(myObjects) { myObjects.clear(); while(...) { // foreach line of my CSV, create a "MyObject" myObjects.add(new MyObject(...)); } } } catch (Exception e) { //... } } } Should I leave the lock only on the myObjects Set, or should I declare the whole parse() method as synchronized ? Also, how should I synchronize - both - the setting of the csvFile and the parsing ? I feel like my actual design is broken because threads could modify the csv file several times while a possibly long parse process is running. I hope I'm being clear enough, because myself am a bit confused on those multi-synchronization issues. Thanks ;-)

    Read the article

  • singleton pattern in Windows Activation Service

    - by Joshua
    Hello I have a few WCF services that are currently being self hosted, in a very basic NT Service. I want to expand my application to add provisioning of WCF Services, and updates, as well as isolation (I want each WCF Service to be in its own AppDomain). These WCF Services contain logic that needs to be run on a regular basis, pinging the database, and getting information from external devices so that when a request comes in the data is readily available. I'm thinking about trying out Windows Activation Service, because i really like the provisioning, and isolation that comes with a managed services infrastructure. If I didn't use WAS I would essentially have to write the same code myself. From what I understand though WAS does not really support the model of having a service that is running before someone actually calls a method on the service. the article I read here MSDN Article Link states "That means in essence that out-of-the-box WAS hosting is not something that is really suited for sessionful or singleton services. It is more suitable for stateless per-call services." it does say that "Out of the box" so I'm wondering if anyone has used WAS to host a WCF service that really behaves more like an NT Service (starting and stopping independantly of having a method called upon it). Or any other ideas would be great. I was planning on writting this infrastructure myself, to host WCF services in a custom ServiceHost, and put their execution in a seporate AppDomain, as well as allow for provision of these services after initial installation, along with updates. However, I would MUCH MUCH MUCH rather not own that code if I don't have to. thanks Joshua

    Read the article

  • Generic Singleton Façade design pattern

    - by Paul
    Hi I try write singleton façade pattern with generics. I have one problem, how can I call method from generic variable. Something like this: T1 t1 = new T1(); //call method from t1 t1.Method(); In method SingletonFasadeMethod I have compile error: Error 1 'T1' does not contain a definition for 'Method' and no extension method 'Method' accepting a first argument of type 'T1' could be found (are you missing a using directive or an assembly reference?) Any advace? Thank, I am beginner in C#. All code is here: namespace GenericSingletonFasade { public interface IMyInterface { string Method(); } internal class ClassA : IMyInterface { public string Method() { return " Calling MethodA "; } } internal class ClassB : IMyInterface { public string Method() { return " Calling MethodB "; } } internal class ClassC : IMyInterface { public string Method() { return "Calling MethodC"; } } internal class ClassD : IMyInterface { public string Method() { return "Calling MethodD"; } } public class SingletonFasade<T1,T2,T3> where T1 : class,new() where T2 : class,new() where T3 : class,new() { private static T1 t1; private static T2 t2; private static T3 t3; private SingletonFasade() { t1 = new T1(); t2 = new T2(); t3 = new T3(); } class SingletonCreator { static SingletonCreator() { } internal static readonly SingletonFasade<T1,T2,T3> uniqueInstace = new SingletonFasade<T1,T2,T3>(); } public static SingletonFasade<T1,T2,T3> UniqueInstace { get { return SingletonCreator.uniqueInstace; } } public string SingletonFasadeMethod() { //Problem is here return t1.Method() + t2.Method() + t3.Method(); } } } I use this for my problem. public class SingletonFasade<T1, T2, T3> where T1 : class, IMyInterface, new() where T2 : class, IMyInterface, new() where T3 : class, IMyInterface, new() {//...} Is any solution without Interfaces ??

    Read the article

  • Singleton Issues in iOS http client

    - by Andrew Lauer Barinov
    I implemented an HTTP client is iOS that is meant to be a singleton. It is a subclass of AFNetworking's excellent AFHTTPClient My access method is pretty standard: + (LBHTTPClient*) sharedHTTPClient { static dispatch_once_t once = 0; static LBHTTPClient *sharedHTTPClient = nil; dispatch_once(&once, ^{ sharedHTTPClient = [[LBHTTPClient alloc] initHTTPClient]; }); return sharedHTTPClient; } // my init method - (id) initHTTPClient { self = [super initWithBaseURL:[NSURL URLWithString:kBaseURL]]; if (self) { // Sub class specific initializations } return self; } Super's init method is very long, and can be found here However the problem I experience is when the dispatch_once queue is run, the app locks and become unresponsive. When I step through code, I notice that it locks on dispatch_once and then remains frozen. Is this something to do with the main thread locking down? How come it stays locked like that? Also, none of the HTTP client methods fire. Stepping through the code some more, I find this line in dispatch/once.h is where the app locks down: DISPATCH_INLINE DISPATCH_ALWAYS_INLINE DISPATCH_NONNULL_ALL DISPATCH_NOTHROW void _dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) { if (DISPATCH_EXPECT(*predicate, ~0l) != ~0l) { dispatch_once(predicate, block); // App locks here } }

    Read the article

  • Singleton EXC_BAD_ACCESS

    - by lclaud
    Hi, so I have a class that I decleare as a singleton and in that class I have a NSMutableArray that contains some NSDictionaries with some key/value pairs in them. The trouble is it doesn't work and I dont't know why... I mean it crashes with EXC_BAD_ACCESS but i don't know where. I followed the code and it did create a new array on first add, made it to the end of the funtion ..and crashed ... @interface dataBase : NSObject { NSMutableArray *inregistrari; } @property (nonatomic,retain) NSMutableArray *inregistrari; -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu; -(NSDictionary *)raportIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)luniDisponibileIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)aniDisponibiliIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)vectorDateIntreData:(NSDate *)dataI siData:(NSDate *)dataF; -(void)salveazaInFisier; -(void)incarcaDinFisier; + (dataBase *)shareddataBase; @end And here is the .m file #import "dataBase.h" #import "SynthesizeSingleton.h" @implementation dataBase @synthesize inregistrari; SYNTHESIZE_SINGLETON_FOR_CLASS(dataBase); -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu{ NSNumber *v=[NSNumber numberWithBool:venit]; NSArray *input=[NSArray arrayWithObjects:data,suma,v,detaliu,nil]; NSArray *keys=[NSArray arrayWithObjects:@"data",@"suma",@"venit",@"detaliu",nil]; NSDictionary *inreg=[NSDictionary dictionaryWithObjects:input forKeys:keys]; if(inregistrari == nil) { inregistrari=[[NSMutableArray alloc ] initWithObjects:inreg,nil]; }else { [inregistrari addObject:inreg]; } [inreg release]; [input release]; [keys release]; } It made it to the end of that adaugaInregistrareCuData ... ok . said the array had one object ... and then crashed

    Read the article

  • Prolog singleton variables in Python

    - by Rubens
    I'm working on a little set of scripts in python, and I came to this: line = "a b c d e f g" a, b, c, d, e, f, g = line.split() I'm quite aware of the fact that these are decisions taken during implementation, but shouldn't (or does) python offer something like: _, _, var_needed, _, _, another_var_needed, _ = line.split() as well as Prolog does offer, in order to exclude the famous singleton variables. I'm not sure, but wouldn't it avoid unnecessary allocation? Or creating references to the result of the split call does not count up as overhead? EDIT: Sorry, my point here is: in Prolog, as far as I'm concerned, in an expression like: test(L, N) :- test(L, 0, N). test([], N, N). test([_|T], M, N) :- V is M + 1, test(T, V, N). The variable represented by _ is not accessible, for what I suppose the reference to the value that does exist in the list [_|T] is not even created. But, in Python, if I use _, I can use the last value assigned to _, and also, I do suppose the assignment occurs for each of the variables _ -- which may be considered an overhead. My question here is if shouldn't there be (or if there is) a syntax to avoid such unnecessary attributions.

    Read the article

  • Understanding the singleton class when aliasing a instance method

    - by Backo
    I am using Ruby 1.9.2 and the Ruby on Rails v3.2.2 gem. I am trying to learn Metaprogramming "the right way" and at this time I am aliasing an instance method in the included do ... end block provided by the RoR ActiveSupport::Concern module: module MyModule extend ActiveSupport::Concern included do # Builds the instance method name. my_method_name = build_method_name.to_sym # => :my_method # Defines the :my_method instance method in the including class of MyModule. define_singleton_method(my_method_name) do |*args| # ... end # Aliases the :my_method instance method in the including class of MyModule. singleton_class = class << self; self end singleton_class.send(:alias_method, :my_new_method, my_method_name) end end "Newbiely" speaking, with a search on the Web I came up with the singleton_class = class << self; self end statement and I used that (instead of the class << self ... end block) in order to scope the my_method_name variable, making the aliasing generated dynamically. I would like to understand exactly why and how the singleton_class works in the above code and if there is a better way (maybe, a more maintainable and performant one) to implement the same (aliasing, defining the singleton method and so on), but "the right way" since I think it isn't so.

    Read the article

  • Generic Singleton Fasade design pattern

    - by Paul
    Hi I try write singleton fasede pattern with generics. I have one problem, how can I call method from generic variable. Something like this: T1 t1 = new T1(); //call method from t1 t1.Method(); In method SingletonFasadeMethod I have compile error: Error 1 'T1' does not contain a definition for 'Method' and no extension method 'Method' accepting a first argument of type 'T1' could be found (are you missing a using directive or an assembly reference?) Any advace? Thank, I am beginner in C#. All code is here: namespace GenericSingletonFasade { public interface IMyInterface { string Method(); } internal class ClassA : IMyInterface { public string Method() { return " Calling MethodA "; } } internal class ClassB : IMyInterface { public string Method() { return " Calling MethodB "; } } internal class ClassC : IMyInterface { public string Method() { return "Calling MethodC"; } } internal class ClassD : IMyInterface { public string Method() { return "Calling MethodD"; } } public class SingletonFasade<T1,T2,T3> where T1 : class,new() where T2 : class,new() where T3 : class,new() { private static T1 t1; private static T2 t2; private static T3 t3; private SingletonFasade() { t1 = new T1(); t2 = new T2(); t3 = new T3(); } class SingletonCreator { static SingletonCreator() { } internal static readonly SingletonFasade<T1,T2,T3> uniqueInstace = new SingletonFasade<T1,T2,T3>(); } public static SingletonFasade<T1,T2,T3> UniqueInstace { get { return SingletonCreator.uniqueInstace; } } public string SingletonFasadeMethod() { //Problem is here return t1.Method() + t2.Method() + t3.Method(); } } }

    Read the article

  • Ninject: Singleton binding syntax?

    - by Rosarch
    I'm using Ninject 2.0 for the .Net 3.5 framework. I'm having difficulty with singleton binding. I have a class UserInputReader which implements IInputReader. I only want one instance of this class to ever be created. public class MasterEngineModule : NinjectModule { public override void Load() { // using this line and not the other two makes it work //Bind<IInputReader>().ToMethod(context => new UserInputReader(Constants.DEFAULT_KEY_MAPPING)); Bind<IInputReader>().To<UserInputReader>(); Bind<UserInputReader>().ToSelf().InSingletonScope(); } } static void Main(string[] args) { IKernel ninject = new StandardKernel(new MasterEngineModule()); MasterEngine game = ninject.Get<MasterEngine>(); game.Run(); } public sealed class UserInputReader : IInputReader { public static readonly IInputReader Instance = new UserInputReader(Constants.DEFAULT_KEY_MAPPING); // ... public UserInputReader(IDictionary<ActionInputType, Keys> keyMapping) { this.keyMapping = keyMapping; } } If I make that constructor private, it breaks. What am I doing wrong here?

    Read the article

  • Using Singleton synchronized array with NSThread

    - by hmthur
    I have a books app with a UISearchBar, where the user types any book name and gets search results (from ext API call) below as he types. I am using a singleton variable in my app called retrievedArray which stores all the books. @interface Shared : NSObject { NSMutableArray *books; } @property (nonatomic, retain) NSMutableArray *books; + (id)sharedManager; @end This is accessed in multiple .m files using NSMutableArray *retrievedArray; ...in the header file retrievedArray = [[Shared sharedManager] books]; My question is how do I ensure that the values inside retrievedArray remain synchronized across all the classes. Actually the values inside retrievedArray gets added through an NSXMLParser (i.e. through external web service API). There is a separate XMLParser.m file, where I do all the parsing and fill the array. The parsing is done on a separate thread. - (void) run: (id) param { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL: [self URL]]; [parser setDelegate: self]; [parser parse]; [parser release]; NSString *tmpURLStr = [[self URL]absoluteString]; NSRange range_srch_book = [tmpURLStr rangeOfString:@"v1/books"]; if (range_srch_book.location != NSNotFound) [delegate performSelectorOnMainThread:@selector(parseDidComplete_srch_book) withObject:nil waitUntilDone:YES]; [pool release]; } - (void) parseXMLFile: (NSURL *) url { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self setURL: url]; NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object: nil]; [retrievedArray removeAllObjects]; [myThread start]; [pool release]; } There seems to be some synchronization issues if the user types very quickly (It seems to be working fine if the user types slowly)....So there are 2 views in which the content of an object in this shared array item is displayed; List and Detail. If user types fast and clicks on A in List view, he is shown B in detail view...That is the main issue. I have tried literally all the solutions I could think of, but am still unable to fix the issue. Please suggest some suitable fixes.

    Read the article

  • boost pool_alloc

    - by mr grumpy
    Why is the boost::fast_pool_allocator built on top of a singleton pool, and not a separate pool per allocator instance? Or to put it another way, why only provide that, and not the option of having a pool per allocator? Would having that be a bad idea? I have a class that internally uses about 10 different boost::unordered_map types. If I'd used the std::allocator then all the memory would go back to the system when it called delete, whereas now I have to call release_memory on many different allocator types at some point. Would I be stupid to roll my own allocator that uses pool instead of singleton_pool? thanks

    Read the article

  • Using OpenGL drawing operations in an object-oriented setting?

    - by Lion Kabob
    I've been plowing through basic shaders and whatnot for an application I'm writing, and I've been having trouble figuring out a high-level organization for the drawing calls. I'm thinking of having a singleton class which implements a number of basic drawing operations, taking data from "user" classes and passing that to the appropriate opengl calls. I'm wondering how people do this when writing their own applications, as the internet is chock full of basic "Your first shader" tutorials, but very little on suggested organization of drawing code. My particular environment is targeted at iPad/OpenGL ES 2.0, but I think the question stands for most environments.

    Read the article

  • PDO Prepare statement not processing parameters

    - by Danten
    I've exhausted all efforts at what appears to be a trivial problem, but gotten nowhere. There is a simple Prepare statement: $qry = $core->db->prepare("SELECT * FROM users WHERE email = '?'"); $qry->execute(array('[email protected]')); However, no rows are returned. Running the query with the parameters hardcoded into the query results in a successful selection of one row. I've tryed many different methods of doing the prepare, but even it this most simple form it isn't working. The PDO object is stored in a singleton called Core. PDO is using the mysql driver.

    Read the article

  • Should member variables of global objects be made global as well?

    - by David Wong
    I'm developing plugins in Eclipse which mandates the use of singleton pattern for the Plugin class in order to access the runtime plugin. The class holds references to objects such as Configuration and Resources. In Eclipse 3.0 plug-in runtime objects are not globally managed and so are not generically accessible. Rather, each plug-in is free to declare API which exposes the plug-in runtime object (e.g., MyPlugin.getInstance() In order for the other components of my system to access these objects, I have to do the following: MyPlugin.getInstance().getConfig().getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER); , which is overly verbose IMO. Since MyPlugin provides global access, wouldn't it be easier for me to just provide global access to the objects it manages as well? MyConfig.getValue(MyPlugin.CONFIGKEY_SOMEPARAMETER); Any thoughts? (I'm actually asking because I was reading about the whole "Global variable access and singletons are evil" debates)

    Read the article

  • iPhone SDK Tableview Datasource singleton error

    - by mrburns05
    I basically followed apple "TheElements" sample and changed "PeriodicElements" .h & .m to my own "SortedItems" .h & .m During compile I get this error: "Undefined symbols: "_OBJC_CLASS_$_SortedItems", referenced from: __objc_classrefs__DATA@0 in SortedByNameTableDataSource.o ld: symbol(s) not found collect2: ld returned 1 exit status " here is my SortedItems.m file #import "SortedItems.h" #import "item.h" #import "MyAppDelegate.h" @interface SortedItems(mymethods) // these are private methods that outside classes need not use - (void)presortItemsByPhysicalState; - (void)presortItemInitialLetterIndexes; - (void)presortItemNamesForInitialLetter:(NSString *)aKey; - (void)presortItemsWithPhysicalState:(NSString *)state; - (NSArray *)presortItemsByNumber; - (NSArray *)presortItemsBySymbol; - (void)setupItemsArray; @end @implementation SortedItems @synthesize statesDictionary; @synthesize itemsDictionary; @synthesize nameIndexesDictionary; @synthesize itemNameIndexArray; @synthesize itemsSortedByNumber; @synthesize itemsSortedBySymbol; @synthesize itemPhysicalStatesArray; static SortedItems *sharedSortedItemsInstance = nil; + (SortedItems*)sharedSortedItems { @synchronized(self) { if (sharedSortedItemsInstance == nil) { [[self alloc] init]; // assignment not done here } } return sharedSortedItemsInstance; // note: Xcode (3.2) static analyzer will report this singleton as a false positive // '(Potential leak of an object allocated') } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedSortedItemsInstance == nil) { sharedSortedItemsInstance = [super allocWithZone:zone]; return sharedSortedItemsInstance; // assignment and return on first allocation } } return nil; //on subsequent allocation attempts return nil } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (unsigned)retainCount { return UINT_MAX; //denotes an object that cannot be released } - (void)release { //do nothing } - (id)autorelease { return self; } // setup the data collection - init { if (self = [super init]) { [self setupItemsArray]; } return self; } - (void)setupItemsArray { NSDictionary *eachItem; // create dictionaries that contain the arrays of Item data indexed by // name self.itemsDictionary = [NSMutableDictionary dictionary]; // physical state self.statesDictionary = [NSMutableDictionary dictionary]; // unique first characters (for the Name index table) self.nameIndexesDictionary = [NSMutableDictionary dictionary]; // create empty array entries in the states Dictionary or each physical state [statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"]; [statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"]; [statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"]; [statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"]; MyAppDelegate *ad = (MyAppDelegate *)[[UIApplication sharedApplication]delegate]; NSMutableArray *rawItemsArray = [[NSMutableArray alloc] init]; [rawItemsArray addObjectsFromArray:ad.items]; // iterate over the values in the raw Items dictionary for (eachItem in rawItemsArray) { // create an atomic Item instance for each Item *anItem = [[Item alloc] initWithDictionary:eachItem]; // store that item in the Items dictionary with the name as the key [itemsDictionary setObject:anItem forKey:anItem.title]; // add that Item to the appropriate array in the physical state dictionary [[statesDictionary objectForKey:anItem.acct] addObject:anItem]; // get the Item's initial letter NSString *firstLetter = [anItem.title substringToIndex:1]; NSMutableArray *existingArray; // if an array already exists in the name index dictionary // simply add the Item to it, otherwise create an array // and add it to the name index dictionary with the letter as the key if (existingArray = [nameIndexesDictionary valueForKey:firstLetter]) { [existingArray addObject:anItem]; } else { NSMutableArray *tempArray = [NSMutableArray array]; [nameIndexesDictionary setObject:tempArray forKey:firstLetter]; [tempArray addObject:anItem]; } // release the Item, it is held by the various collections [anItem release]; } // release the raw Item data [rawItemsArray release]; // create the dictionary containing the possible Item states // and presort the states data self.itemPhysicalStatesArray = [NSArray arrayWithObjects:@"something",@"somethingElse",@"whatever",@"stuff",nil]; [self presortItemsByPhysicalState]; // presort the dictionaries now // this could be done the first time they are requested instead [self presortItemInitialLetterIndexes]; self.itemsSortedByNumber = [self presortItemsByNumber]; self.itemsSortedBySymbol = [self presortItemsBySymbol]; } // return the array of Items for the requested physical state - (NSArray *)itemsWithPhysicalState:(NSString*)aState { return [statesDictionary objectForKey:aState]; } // presort each of the arrays for the physical states - (void)presortItemsByPhysicalState { for (NSString *stateKey in itemPhysicalStatesArray) { [self presortItemsWithPhysicalState:stateKey]; } } - (void)presortItemsWithPhysicalState:(NSString *)state { NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] ; NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor]; [[statesDictionary objectForKey:state] sortUsingDescriptors:descriptors]; [nameDescriptor release]; } // return an array of Items for an initial letter (ie A, B, C, ...) - (NSArray *)itemsWithInitialLetter:(NSString*)aKey { return [nameIndexesDictionary objectForKey:aKey]; } // presort the name index arrays so the items are in the correct order - (void)presortItemsInitialLetterIndexes { self.itemNameIndexArray = [[nameIndexesDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; for (NSString *eachNameIndex in itemNameIndexArray) { [self presortItemNamesForInitialLetter:eachNameIndex]; } } - (void)presortItemNamesForInitialLetter:(NSString *)aKey { NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] ; NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor]; [[nameIndexesDictionary objectForKey:aKey] sortUsingDescriptors:descriptors]; [nameDescriptor release]; } // presort the ItemsSortedByNumber array - (NSArray *)presortItemsByNumber { NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"acct" ascending:YES selector:@selector(compare:)] ; NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor]; NSArray *sortedItems = [[itemsDictionary allValues] sortedArrayUsingDescriptors:descriptors]; [nameDescriptor release]; return sortedItems; } // presort the itemsSortedBySymbol array - (NSArray *)presortItemsBySymbol { NSSortDescriptor *symbolDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] ; NSArray *descriptors = [NSArray arrayWithObject:symbolDescriptor]; NSArray *sortedItems = [[itemsDictionary allValues] sortedArrayUsingDescriptors:descriptors]; [symbolDescriptor release]; return sortedItems; } @end I followed the sample exactly - don't know where I went wrong. Here is my "SortedByNameTableDataSource.m" #import "SortedByNameTableDataSource.h" #import "SortedItems.h" #import "Item.h" #import "ItemCell.h" #import "GradientView.h" #import "UIColor-Expanded.h" #import "MyAppDelegate.h" @implementation SortedByNameTableDataSource - (NSString *)title { return @"Title"; } - (UITableViewStyle)tableViewStyle { return UITableViewStylePlain; }; // return the atomic element at the index - (Item *)itemForIndexPath:(NSIndexPath *)indexPath { return [[[SortedItems sharedSortedItems] itemsWithInitialLetter:[[[SortedItems sharedSortedItems] itemNameIndexArray] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]; } // UITableViewDataSource methods - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"ItemCell"; ItemCell *itemCell = (ItemCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (itemCell == nil) { itemCell = [[[ItemCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; itemCell = CGRectMake(0.0, 0.0, 320.0, ROW_HEIGHT); itemCell.backgroundView = [[[GradientView alloc] init] autorelease]; } itemCell.todo = [self itemForIndexPath:indexPath]; return itemCell; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // this table has multiple sections. One for each unique character that an element begins with // [A,B,C,D,E,F,G,H,I,K,L,M,N,O,P,R,S,T,U,V,X,Y,Z] // return the count of that array return [[[SortedItems sharedSortedItems] itemNameIndexArray] count]; } - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { // returns the array of section titles. There is one entry for each unique character that an element begins with // [A,B,C,D,E,F,G,H,I,K,L,M,N,O,P,R,S,T,U,V,X,Y,Z] return [[SortedItems sharedSortedItems] itemNameIndexArray]; } - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { return index; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // the section represents the initial letter of the element // return that letter NSString *initialLetter = [[[SortedItems sharedSortedItems] itemNameIndexArray] objectAtIndex:section]; // get the array of elements that begin with that letter NSArray *itemsWithInitialLetter = [[SortedItems sharedSortedItems] itemsWithInitialLetter:initialLetter]; // return the count return [itemsWithInitialLetter count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { // this table has multiple sections. One for each unique character that an element begins with // [A,B,C,D,E,F,G,H,I,K,L,M,N,O,P,R,S,T,U,V,X,Y,Z] // return the letter that represents the requested section // this is actually a delegate method, but we forward the request to the datasource in the view controller return [[[SortedItems sharedSortedItems] itemNameIndexArray] objectAtIndex:section]; } @end

    Read the article

  • Need advice on OOP philosophy

    - by David Jenings
    I'm trying to get the wheels turning on a large project in C#. My previous experience is in Delphi, where by default every form was created at applicaton startup and form references where held in (gasp) global variables. So I'm trying to adapt my thinking to a 100% object oriented environment, and my head is spinning just a little. My app will have a large collection of classes Most of these classes will only really need one instance. So I was thinking: static classes. I'm not really sure why, but much of what I've read here says that if my class is going to hold a state, which I take to mean any property values at all, I should use a singleton structure instead. Okay. But there are people out there who for reasons that escape me, think that singletons are evil too. None of these classes is in danger of being used anywhere except in this program. So they could certainly work fine as regular objects (vs singletons or static classes) Then there's the issue of interaction between objects. I'm tempted to create a Global class full of public static properties referencing the single instances of many of these classes. I've also considered just making them properties (static or instance, not sure which) of the MainForm. Then I'd have each of my classes be aware of the MainForm as Owner. Then the various objects could refer to each other as Owner.Object1, Owner.Object2, etc. I fear I'm running out of electronic ink, or at least taxing the patience of anyone kind enough to have stuck with me this long. I hope I have clearly explained my state of utter confusion. I'm just looking for some advice on best practices in my situation. All input is welcome and appreciated. Thanks in advance, David Jennings

    Read the article

  • In Ruby, how to implement global behaviour?

    - by Gordon McAllister
    Hi all, I want to implement the concept of a Workspace. This is a global concept - all other code will interact with one instance of this Workspace. The Workspace will be responsible for maintaining the current system state (i.e. interacting with the system model, persisting the system state etc) So what's the best design strategy for my Workspace, bearing in mind this will have to be testable (using RSpec now, but happy to look at alternatives). Having read thru some open source projects out there and I've seen 3 strategies. None of which I can identify as "the best practice". They are: Include the singleton class. But how testable is this? Will the global state of Workspace change between tests? Implemented all behaviour as class methods. Again how do you test this? Implemented all behaviour as module methods. Not sure about this one at all! Which is best? Or is there another way? Thanks, Gordon

    Read the article

  • How to delay static initialization within a property

    - by Mystagogue
    I've made a class that is a cross between a singleton (fifth version) and a (dependency injectable) factory. Call this a "Mono-Factory?" It works, and looks like this: public static class Context { public static BaseLogger LogObject = null; public static BaseLogger Log { get { return LogFactory.instance; } } class LogFactory { static LogFactory() { } internal static readonly BaseLogger instance = LogObject ?? new BaseLogger(null, null, null); } } //USAGE EXAMPLE: //Optional initialization, done once when the application launches... Context.LogObject = new ConLogger(); //Example invocation used throughout the rest of code... Context.Log.Write("hello", LogSeverity.Information); The idea is for the mono-factory could be expanded to handle more than one item (e.g. more than a logger). But I would have liked to have made the mono-factory look like this: public static class Context { private static BaseLogger LogObject = null; public static BaseLogger Log { get { return LogFactory.instance; } set { LogObject = value; } } class LogFactory { static LogFactory() { } internal static readonly BaseLogger instance = LogObject ?? new BaseLogger(null, null, null); } } The above does not work, because the moment the Log property is touched (by a setter invocation) it causes the code path related to the getter to be executed...which means the internal LogFactory "instance" data is always set to the BaseLogger (setting the "LogObject" is always too late!). So is there a decoration or other trick I can use that would cause the "get" path of the Log property to be lazy while the set path is being invoked?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >