Search Results

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

Page 5/31 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Circular reference problem Singleton

    - by Ismail
    I'm trying to creating a Singleton class like below where MyRepository lies in separate DAL project. It's causing me a circular reference problem because GetMySingleTon() method returns MySingleTon class and needs its access. Same way I need MyRepository access in constructor of MySingleTon class. public class MySingleTon { static MySingleTon() { if (Instance == null) { MyRepository rep = new MyRepository(); Instance = rep.GetMySingleTon(); } } public static MySingleTon Instance { get; private set; } public string prop1 { get; set; } public string prop2 { get; set; } }

    Read the article

  • Generic Abstract Singleton with Custom Constructor in C#

    - by Heka
    I want to write a generic singleton with an external constructor. In other words the constructor can be modified. I have 2 designs in my mind but I don't know whether they are practical or not. First one is to enforce derived class' constructor to be non-public but I do not know if there is a way of it? Second one is to use a delegate and call it inside the constructor? It isn't necessarily to be a constructor. The reason I chose custom constructor is doing some custom initializations. Any suggestions would be appreciated :)

    Read the article

  • StructureMap 'conditional singleton' for Lucene.Net IndexReader

    - by Gareth D
    I have a threadsafe object that is expensive to create and needs to be available through my application (a Lucene.Net IndexReader). The object can become invalid, at which point I need to recreate it (IndexReader.IsCurrent is false, need a new instance using IndexReader.Reopen). I'd like to able to use an IoC container (StructureMap) to manage the creation of the object, but I can't work out if this scenario is possible. It feels like some kind of "conditional singleton" lifecycle. Does StructureMap provide such a feature? Any alternative suggestions?

    Read the article

  • Thread-safe use of a singleton's members

    - by Anthony Mastrean
    I have a C# singleton class that multiple classes use. Is access through Instance to the Toggle() method thread-safe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it? public class MyClass { private static readonly MyClass instance = new MyClass(); public static MyClass Instance { get { return instance; } } private int value = 0; public int Toggle() { if(value == 0) { value = 1; } else if(value == 1) { value = 0; } return value; } }

    Read the article

  • C++ boost thread id and Singleton

    - by aaa
    hi. Sorry to flood so many questions this week. I assume thread index returned by thread.get_id is implementation specific. In case of the pthreads, is index reused? IE, if thread 0 runs and joins, is thread launched afterwords going to have a different ID? the reason I ask this is a need to implement Singleton pattern with a twist: each thread gets its own instance. I know it sounds very crazy, but threads control hardware (cuda) which does not permit device memory sharing. What is a good way to implement such pattern?

    Read the article

  • StructureMap singleton behavior not working

    - by user137348
    My code is public static class ContainerBootstrapper { public static void BootstrapStructureMap() { ObjectFactory.Initialize(x => x .ForRequestedType<ValueHolder>() .CacheBy(InstanceScope.Singleton) .TheDefaultIsConcreteType<ValueHolder>()); } } Initialization code (its a windows service) static class Program { static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new AppServer() }; ServiceBase.Run(ServicesToRun); ContainerBootstrapper.BootstrapStructureMap(); } } And then I call an instance like this: var valueHolder = ObjectFactory.GetInstance<ValueHolder>(); But I get everytime an new instance not the one used before.

    Read the article

  • singleton pattern in java- lazy Intialization

    - by flash
    public static MySingleton getInstance() { if (_instance==null) { synchronized (MySingleton.class) { _instance = new MySingleton(); } } return _instance; } 1.is there a flaw with the above implementation of the getInstance method? 2.What is the difference between the two implementations.? public static synchronized MySingleton getInstance() { if (_instance==null) { _instance = new MySingleton(); } return _instance; } I have seen a lot of answers on the singleton pattern in stackoverflow but the question I have posted is to know mainly difference of 'synchronize' at method and block level in this particular case.

    Read the article

  • how do you make a "concurrent queue safe" lazy loader (singleton manager) in objective-c

    - by Rich
    Hi, I made this class that turns any object into a singleton, but I know that it's not "concurrent queue safe." Could someone please explain to me how to do this, or better yet, show me the code. To be clear I want to know how to use this with operation queues and dispatch queues (NSOperationQueue and Grand Central Dispatch) on iOS. Thanks in advance, Rich EDIT: I had an idea for how to do it. If someone could confirm it for me I'll do it and post the code. The idea is that proxies make queues all on their own. So if I make a mutable proxy (like Apple does in key-value coding/observing) for any object that it's supposed to return, and always return the same proxy for the same object/identifier pair (using the same kind of lazy loading technique as I used to create the singletons), the proxies would automatically queue up the any messages to the singletons, and make it totally thread safe. IMHO this seems like a lot of work to do, so I don't want to do it if it's not gonna work, or if it's gonna slow my apps down to a crawl. Here's my non-thread safe code: RMSingletonCollector.h // // RMSingletonCollector.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import <Foundation/Foundation.h> #import "RMWeakObjectRef.h" struct RMInitializerData { // The method may take one argument. // required SEL designatedInitializer; // data to pass to the initializer or nil. id data; }; typedef struct RMInitializerData RMInitializerData; RMInitializerData RMInitializerDataMake(SEL initializer, id data); @interface NSObject (SingletonCollector) // Returns the selector and data to pass to it (if the selector takes an argument) for use when initializing the singleton. // If you override this DO NOT call super. + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier; @end @interface RMSingletonCollector : NSObject { } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier; + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier; + (void)destroyCollection; + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier; @end // ==--==--==--==--==Notifications==--==--==--==--== extern NSString *const willDestroySingletonCollection; extern NSString *const willDestroySingletonCollectionObject; RMSingletonCollector.m // // RMSingletonCollector.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMSingletonCollector.h" #import <objc/objc-runtime.h> NSString *const willDestroySingletonCollection = @"willDestroySingletonCollection"; NSString *const willDestroySingletonCollectionObject = @"willDestroySingletonCollectionObject"; RMInitializerData RMInitializerDataMake(SEL initializer, id data) { RMInitializerData newData; newData.designatedInitializer = initializer; newData.data = data; return newData; } @implementation NSObject (SingletonCollector) + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier { return RMInitializerDataMake(@selector(init), nil); } @end @interface RMSingletonCollector () + (NSMutableDictionary *)singletonCollection; + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection; @end @implementation RMSingletonCollector static NSMutableDictionary *singletonCollection = nil; + (NSMutableDictionary *)singletonCollection { if (singletonCollection != nil) { return singletonCollection; } NSMutableDictionary *collection = [[NSMutableDictionary alloc] initWithCapacity:1]; [self setSingletonCollection:collection]; [collection release]; return singletonCollection; } + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection { if (newSingletonCollection != singletonCollection) { [singletonCollection release]; singletonCollection = [newSingletonCollection retain]; } } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier { id obj; NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } if (obj = [[self singletonCollection] objectForKey:key]) { return obj; } // dynamic creation. // get a class for Class classForName = NSClassFromString(className); if (classForName) { obj = objc_msgSend(classForName, @selector(alloc)); // if the initializer takes an argument... RMInitializerData initializerData = [classForName designatedInitializerForIdentifier:identifier]; if (initializerData.data) { // pass it. obj = objc_msgSend(obj, initializerData.designatedInitializer, initializerData.data); } else { obj = objc_msgSend(obj, initializerData.designatedInitializer); } [singletonCollection setObject:obj forKey:key]; [obj release]; } else { // raise an exception if there is no class for the specified name. NSException *exception = [NSException exceptionWithName:@"com.RMDev.RMSingletonCollector.failed_to_find_class" reason:[NSString stringWithFormat:@"SingletonCollector couldn't find class for name: %@", [className description]] userInfo:nil]; [exception raise]; [exception release]; } return obj; } + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier { id obj = [self collectionObjectForType:className identifier:identifier]; RMWeakObjectRef *objectRef = [[RMWeakObjectRef alloc] initWithObject:obj identifier:identifier]; return [objectRef autorelease]; } + (void)destroyCollection { NSDictionary *userInfo = [singletonCollection copy]; [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollection object:self userInfo:userInfo]; [userInfo release]; // release the collection and set it to nil. [self setSingletonCollection:nil]; } + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier { NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollectionObject object:[singletonCollection objectForKey:key] userInfo:nil]; [singletonCollection removeObjectForKey:key]; } @end RMWeakObjectRef.h // // RMWeakObjectRef.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // // In order to offset the performance loss from always having to search the dictionary, I made a retainable, weak object reference class. #import <Foundation/Foundation.h> @protocol RMWeakObjectReference <NSObject> @property (nonatomic, assign, readonly) id objectRef; @property (nonatomic, retain, readonly) NSString *className; @property (nonatomic, retain, readonly) NSString *objectIdentifier; @end @interface RMWeakObjectRef : NSObject <RMWeakObjectReference> { id objectRef; NSString *className; NSString *objectIdentifier; } - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier; - (void)objectWillBeDestroyed:(NSNotification *)notification; @end RMWeakObjectRef.m // // RMWeakObjectRef.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMWeakObjectRef.h" #import "RMSingletonCollector.h" @implementation RMWeakObjectRef @dynamic objectRef; @synthesize className, objectIdentifier; - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier { if (self = [super init]) { NSString *classNameForObject = NSStringFromClass([object class]); className = classNameForObject; objectIdentifier = identifier; objectRef = object; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollectionObject object:object]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollection object:[RMSingletonCollector class]]; } return self; } - (id)objectRef { if (objectRef) { return objectRef; } objectRef = [RMSingletonCollector collectionObjectForType:className identifier:objectIdentifier]; return objectRef; } - (void)objectWillBeDestroyed:(NSNotification *)notification { objectRef = nil; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [className release]; [super dealloc]; } @end

    Read the article

  • singleton factory connection pdo

    - by Scarface
    Hey guys I am having a lot of trouble trying to understand this and I was just wondering if someone could help me with some questions. I found some code that is supposed to create a connection with pdo. The problem I was having was having my connection defined within functions. Someone suggested globals but then pointed to a 'better' solution http://stackoverflow.com/questions/130878/global-or-singleton-for-database-connection. My questions with this code are. PS I cannot format this code on this page so see the link if you cannot read What is the point of the connection factory? What goes inside new ConnectionFactory(...) When the connection is defined $db = new PDO(...); why is there no try or catch (I use those for error handling)? Does this then mean I have to use try and catch for every subsequent query? class ConnectionFactory { private static $factory; public static function getFactory() { if (!self::$factory) self::$factory = new ConnectionFactory(...); return self::$factory; } private $db; public function getConnection() { if (!$db) $db = new PDO(...); return $db; } } function getSomething() { $conn = ConnectionFactory::getFactory()-getConnection(); . . . }

    Read the article

  • javascript plugin - singleton pattern?

    - by Adam Kiss
    intro Hello, I'm trying to develop some plugin or/*and* object in javascript, which will control some properties over some object. It will also use jQuery, to ease development. idea This is in pseudocode to give you an idea, since I can't really describe it in english with the right words, it's impossible to go and use google to find out what I want to use (and learn). I will have plugin (maybe object?) with some variables and methods: plugin hideshow(startupconfig){ var c, //collection add: function(what){ c += what; }, do: function(){ c.show().hide().stop(); //example code } } and I will use it this way (or sort-of): var p = new Plugin(); p .add($('p#simple')) .add($('p#simple2')) .do(); note I'm not really looking for jQuery plugin tutorials - it's more like usage of singleton pattern in document in javascript, jQuery is mentione only because it will be used to modify dom and simplify selectors, jQuery plugin maybe just for that one little function add. I'm looking for something, that will sit on top of my document and call functions from itselft based on timer, or user actions, or whatever. problems I don't really know where to start with construction of this object/plugin I'm not really sure how to maintain one variable, which is collection of jQuery objects (something like $('#simple, #simple2');) I would maybe like to extedn jQuery with $.fn.addToPlugin to use chaining of objects, but that should be simple (really just each( p.add($(this)); )) I hope I make any sense, ideas, links or advices appreciated.

    Read the article

  • java singleton instantiation

    - by jurchiks
    I've found three ways of instantiating a Singleton, but I have doubts as to whether any of them is the best there is. I'm using them in a multi-threaded environment and prefer lazy instantiation. Sample 1: private static final ClassName INSTANCE = new ClassName(); public static ClassName getInstance() { return INSTANCE; } Sample 2: private static class SingletonHolder { public static final ClassName INSTANCE = new ClassName(); } public static ClassName getInstance() { return SingletonHolder.INSTANCE; } Sample 3: private static ClassName INSTANCE; public static synchronized ClassName getInstance() { if (INSTANCE == null) INSTANCE = new ClassName(); return INSTANCE; } The project I'm using ATM uses Sample 2 everywhere, but I kind of like Sample 3 more. There is also the Enum version, but I just don't get it. The question here is - in which cases I should/shouldn't use any of these variations? I'm not looking for lengthy explanations though (there's plenty of other topics about that, but they all eventually turn into arguing IMO), I'd like it to be understandable with few words.

    Read the article

  • Dependency Injection into your Singleton

    - by Langali
    I have a singleton that has a spring injected Dao (simplified below): public class MyService<T> implements Service<T> { private final Map<String, T> objects; private static MyService instance; MyDao myDao; public void set MyDao(MyDao myDao) { this. myDao = myDao; } private MyService() { this.objects = Collections.synchronizedMap(new HashMap<String, T>()); // start a background thread that runs for ever } public static synchronized MyService getInstance() { if(instance == null) { instance = new MyService(); } return instance; } public void doSomething() { myDao.persist(objects); } } My spring config will probably look like this: <bean id="service" class="MyService" factory-method="getInstance"/> But this will instantiate the MyService during startup. Is there a programmatic way to do a dependency injection of MyDao into MyService, but not have spring manage the MyService? Basically I want to be able to do this from my code: MyService.getInstance().doSomething(); while having spring inject the MyDao for me.

    Read the article

  • PHP OOP singleton doesn't return object

    - by Misiur
    Weird trouble. I've used singleton multiple times but this particular case just doesn't want to work. Dump says that instance is null. define('ROOT', "/"); define('INC', 'includes/'); define('CLS', 'classes/'); require_once(CLS.'Core/Core.class.php'); $core = Core::getInstance(); var_dump($core->instance); $core->settings(INC.'config.php'); $core->go(); Core class class Core { static $instance; public $db; public $created = false; private function __construct() { $this->created = true; } static function getInstance() { if(!self::$instance) { self::$instance = new Core(); } else { return self::$instance; } } public function settings($path = null) { ... } public function go() { ... } } Error code Fatal error: Call to a member function settings() on a non-object in path It's possibly some stupid typo, but I don't have any errors in my editor. Thanks for the fast responses as always.

    Read the article

  • Using block around a static/singleton resource reference

    - by byte
    This is interesting (to me anyway), and I'd like to see if anyone has a good answer and explanation for this behavior. Say you have a singleton database object (or static database object), and you have it stored in a class Foo. public class Foo { public static SqlConnection DBConn = new SqlConnection(ConfigurationManager.ConnectionStrings["BAR"].ConnectionString); } Then, lets say that you are cognizant of the usefulness of calling and disposing your connection (pretend for this example that its a one-time use for purposes of illustration). So you decide to use a 'using' block to take care of the Dispose() call. using (SqlConnection conn = Foo.DBConn) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "SP_YOUR_PROC"; cmd.ExecuteNonQuery(); } conn.Close(); } This fails, with an error stating that the "ConnectionString property is not initialized". It's not an issue with pulling the connection string from the app.config/web.config. When you investigate in a debug session you see that Foo.DBConn is not null, but contains empty properties. Why is this?

    Read the article

  • efficient thread-safe singleton in C++

    - by user168715
    The usual pattern for a singleton class is something like static Foo &getInst() { static Foo *inst = NULL; if(inst == NULL) inst = new Foo(...); return *inst; } However, it's my understanding that this solution is not thread-safe, since 1) Foo's constructor might be called more than once (which may or may not matter) and 2) inst may not be fully constructed before it is returned to a different thread. One solution is to wrap a mutex around the whole method, but then I'm paying for synchronization overhead long after I actually need it. An alternative is something like static Foo &getInst() { static Foo *inst = NULL; if(inst == NULL) { pthread_mutex_lock(&mutex); if(inst == NULL) inst = new Foo(...); pthread_mutex_unlock(&mutex); } return *inst; } Is this the right way to do it, or are there any pitfalls I should be aware of? For instance, are there any static initialization order problems that might occur, i.e. is inst always guaranteed to be NULL the first time getInst is called?

    Read the article

  • Using a Data Management Singleton

    - by Dan Ray
    Here's my singleton code (pretty much boilerplate): @interface DataManager : NSObject { NSMutableArray *eventList; } @property (nonatomic, retain) NSMutableArray *eventList; +(DataManager*)sharedDataManager; @end And then the .m: #import "DataManager.h" static DataManager *singletonDataManager = nil; @implementation DataManager @synthesize eventList; +(DataManager*)sharedDataManager { @synchronized(self) { if (!singletonDataManager) { singletonDataManager = [[DataManager alloc] init]; } } NSLog(@"Pulling a copy of shared manager."); return singletonDataManager; } So then in my AppDelegate, I load some stuff before launching my first view: NSMutableArray *eventList = [DataManager sharedDataManager].eventList; .... NSLog(@"Adding event %@ to eventList", event.title); [eventList addObject:event]; NSLog(@"eventList now has %d members", [eventList count]); [event release]; As you can see, I've peppered the code with NSLog love notes to myself. The output to the Log reads like: 2010-05-10 09:08:53.355 MyApp[2037:207] Adding event Woofstock Music Festival to eventList 2010-05-10 09:08:53.355 MyApp[2037:207] eventList now has 0 members 2010-05-10 09:08:53.411 MyApp[2037:207] Adding event Test Event for Staging to eventList 2010-05-10 09:08:53.411 MyApp[2037:207] eventList now has 0 members 2010-05-10 09:08:53.467 MyApp[2037:207] Adding event Montgomery Event to eventList 2010-05-10 09:08:53.467 MyApp[2037:207] eventList now has 0 members 2010-05-10 09:08:53.524 MyApp[2037:207] Adding event Alamance County Event For June to eventList 2010-05-10 09:08:53.524 MyApp[2037:207] eventList now has 0 members ... What gives? I have no errors getting to my eventList NSMutableArray. But I addObject: fails silently?

    Read the article

  • Create table class as a singleton

    - by Mark
    I got a class that I use as a table. This class got an array of 16 row classes. These row classes all have 6 double variables. The values of these rows are set once and never change. Would it be a good practice to make this table a singleton? The advantage is that it cost less memory, but the table will be called from multiple threads so I have to synchronize my code which way cause a bit slower application. However lookups in this table are probably a very small portion of the total code that is executed. EDIT: This is my code, are there better ways to do this or is this a good practice? Removed synchronized keyword according to recommendations in this question. final class HalfTimeTable { private HalfTimeRow[] table = new HalfTimeRow[16]; private static final HalfTimeTable instance = new HalfTimeTable(); private HalfTimeTable() { if (instance != null) { throw new IllegalStateException("Already instantiated"); } table[0] = new HalfTimeRow(4.0, 1.2599, 0.5050, 1.5, 1.7435, 0.1911); table[1] = new HalfTimeRow(8.0, 1.0000, 0.6514, 3.0, 1.3838, 0.4295); //etc } @Override @Deprecated public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } public static HalfTimeTable getInstance() { return instance; } public HalfTimeRow getRow(int rownumber) { return table[rownumber]; } }

    Read the article

  • VB.NET looping through XML to store in singleton

    - by rockinthesixstring
    I'm having a problem with looping through an XML file and storing the value in a singleton My XML looks like this <values> <value></value> <value>$1</value> <value>$5,000</value> <value>$10,000</value> <value>$15,000</value> <value>$25,000</value> <value>$50,000</value> <value>$75,000</value> <value>$100,000</value> <value>$250,000</value> <value>$500,000</value> <value>$750,000</value> <value>$1,000,000</value> <value>$1,250,000</value> <value>$1,500,000</value> <value>$1,750,000</value> <value>$2,000,000</value> <value>$2,500,000</value> <value>$3,000,000</value> <value>$4,000,000</value> <value>$5,000,000</value> <value>$7,500,000</value> <value>$10,000,000</value> <value>$15,000,000</value> <value>$25,000,000</value> <value>$50,000,000</value> <value>$100,000,000</value> <value>$100,000,000+</value> </values> And my function looks like this Public Class LoadValues Private Shared SearchValuesInstance As List(Of SearchValues) = Nothing Public Shared ReadOnly Property LoadSearchValues As List(Of SearchValues) Get Dim sv As New List(Of SearchValues) If SearchValuesInstance Is Nothing Then Dim objDoc As XmlDocument = New XmlDataDocument Dim objRdr As XmlTextReader = New XmlTextReader(HttpContext.Current.Server.MapPath("~/App_Data/Search-Values.xml")) objRdr.Read() objDoc.Load(objRdr) Dim root As XmlElement = objDoc.DocumentElement Dim itemNodes As XmlNodeList = root.SelectNodes("/values") For Each n As XmlNode In itemNodes sv.Add(New SearchValues(n("@value").InnerText, n("@value").InnerText)) Next SearchValuesInstance = sv Else : sv = SearchValuesInstance End If Return sv End Get End Property End Class My problem is that I'm getting an object not set to an instance of an object on the sv.Add(New SearchValues(n("@value").InnerText, n("@value").InnerText)) line.

    Read the article

  • Should I create protected constructor for my singleton classes?

    - by Vijay Shanker
    By design, in Singleton pattern the constructor should be marked private and provide a creational method retuning the private static member of the same type instance. I have created my singleton classes like this only. public class SingletonPattern {// singleton class private static SingletonPattern pattern = new SingletonPattern(); private SingletonPattern() { } public static SingletonPattern getInstance() { return pattern; } } Now, I have got to extend a singleton class to add new behaviors. But the private constructor is not letting be define the child class. I was thinking to change the default constructor to protected constructor for the singleton base class. What can be problems, if I define my constructors to be protected? Looking for expert views....

    Read the article

  • Problem with SIngleton Class

    - by zp26
    Hi, I have a prblem with my code. I have a viewController and a singleton class. When i call the method readXml and run a for my program update the UITextView. When i call the clearTextView method the program exit with EXC_BAD_ACCESS. The prblem it's the name of the variable position. This is invalid but i don't change anything between the two methods. You have an idea? My code: #import "PositionIdentifierViewController.h" #import "WriterXML.h" #import "ParserXML.h" #define timeToScan 0.1 @implementation PositionIdentifierViewController @synthesize accelerometer; @synthesize actualPosition; @synthesize actualX; @synthesize actualY; @synthesize actualZ; -(void)updateTextView:(NSString*)nomePosizione { NSString *string = [NSString stringWithFormat:@"%@",nomePosizione]; textEvent.text = [textEvent.text stringByAppendingString:@"\n"]; textEvent.text = [textEvent.text stringByAppendingString:string]; } -(IBAction)clearTextEvent{ textEvent.text = @""; //with this for my program exit for(int i=0; i<[[sharedController arrayPosition]count]; i++){ NSLog(@"sononelfor"); Position *tempPosition = [[Position alloc]init]; tempPosition = [[sharedController arrayPosition]objectAtIndex:i]; [self updateTextView:(NSString*)[tempPosition name]]; } } -(void)readXml{ if([sharedController readXml]){ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Caricamento Posizioni" message:@"Caricamento effettuato con successo" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; [alert release]; NSString *string = [NSString stringWithFormat:@"%d", [[sharedController arrayPosition]count]]; [self updateTextView:(NSString*)string]; //with only this the program is ok for(int i=0; i<[[sharedController arrayPosition]count]; i++){ NSLog(@"sononelfor"); Position *tempPosition = [[Position alloc]init]; tempPosition = [[sharedController arrayPosition]objectAtIndex:i]; [self updateTextView:(NSString*)[tempPosition name]]; } } else{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Caricamento Posizioni" message:@"Caricamento non riuscito" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; [alert release]; } } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; sharedController = [SingletonController sharedSingletonController]; actualPosition = [[Position alloc]init]; self.accelerometer = [UIAccelerometer sharedAccelerometer]; self.accelerometer.updateInterval = timeToScan; self.accelerometer.delegate = self; actualX=0; actualY=0; actualZ=0; [self readXml]; } - (void)dealloc { [super dealloc]; [actualPosition dealloc]; [super dealloc]; } @end #import "SingletonController.h" #import "Position.h" #import "WriterXML.h" #import "ParserXML.h" #define standardSensibility 2 #define timeToScan .1 @implementation SingletonController @synthesize arrayPosition; @synthesize arrayMovement; @synthesize actualPosition; @synthesize actualMove; @synthesize stopThread; +(SingletonController*)sharedSingletonController{ static SingletonController *sharedSingletonController; @synchronized(self) { if(!sharedSingletonController){ sharedSingletonController = [[SingletonController alloc]init]; } } return sharedSingletonController; } -(BOOL)readXml{ ParserXML *newParser = [[ParserXML alloc]init]; if([newParser startParsing:(NSString*)@"filePosizioni.xml"]){ [arrayPosition addObjectsFromArray:[newParser arrayPosition]]; return TRUE; } else return FALSE; } -(id)init{ self = [super init]; if (self != nil) { arrayPosition = [[NSMutableArray alloc]init]; arrayMovement = [[NSMutableArray alloc]init]; actualPosition = [[Position alloc]init]; actualMove = [[Movement alloc]init]; stopThread = FALSE; } return self; } -(void) dealloc { [super dealloc]; } @end

    Read the article

  • How To Create Per-Request Singleton in Pylons?

    - by dave mankoff
    In our Pylons based web-app, we're creating a class that essentially provides some logging functionality. We need a new instance of this class for each http request that comes in, but only one per request. What is the proper way to go about this? Should we just create the object in middleware and store in in request.environ? Is there a more appropriate way to go about this?

    Read the article

  • PDO using singleton stored as class properity

    - by Misiur
    Hi again. OOP drives me crazy. I can't move PDO to work. Here's my DB class: class DB extends PDO { public function &instance($dsn, $username = null, $password = null, $driver_options = array()) { static $instance = null; if($instance === null) { try { $instance = new self($dsn, $username, $password, $driver_options); } catch(PDOException $e) { throw new DBException($e->getMessage()); } } return $instance; } } It's okay when i do something like this: try { $db = new DB(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } catch(DBException $e) { echo $e->getMessage(); } But this: try { $db = DB::instance(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } catch(DBException $e) { echo $e->getMessage(); } Does nothing. I mean, even when I use wrong password/username, I don't get any exception. Second thing - I have class which is "heart" of my site: class Core { static private $instance; public $db; public function __construct() { if(!self::$instance) { $this->db = DB::instance(DB_TYPE.':hpost='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } return self::$instance; } private function __clone() { } } I've tried to use "new DB" inside class, but this: $r = $core->db->query("SELECT * FROM me_config"); print_r($r->fetch()); Return nothing. $sql = "SELECT * FROM me_config"; print_r($core->db->query($sql)); I get: PDOStatement Object ( [queryString] => SELECT * FROM me_config ) I'm really confused, what am I doing wrong?

    Read the article

  • What is design principle behind Servlets being Singleton

    - by Sandeep Jindal
    A servlet container "generally" create one instance of a servlet and different threads of the same instance to serve multiple requests. (I know this can be changed using deprecated SingleThreadModel and other features, but this is the usual way). I thought, the simple reason behind this is performance gain, as creating threads is better than creating instances. But it seems this is not the reason. On the other hand, creating instances have little advantage that developers never have to worry about thread safety. I am trying to understand the reason for this decision over the trade-off of thread-safety.

    Read the article

  • Is this a correct implementation of singleton C++?

    - by Kamal
    class A{ static boost::shared_ptr<A> getInstance(){ if(pA==NULL){ pA = new A(); } return boost::shared_ptr(pA); } //destructor ~A(){ delete pA; pA=NULL; } private: A(){ //some initialization code } //private assigment and copy constructors A(A const& copy); // Not Implemented A& operator=(A const& copy); // Not Implemented static A* pA; }; A* A::pA = NULL;

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >